本文介绍了创建一个求和函数,仅对向量的一部分求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

显然我需要一个求和函数,而累加不会削减它

Obviously I need a sum function for this and accumulate will not cut it

我需要创建程序 - 一个向量 - 用户可以指定 n 个元素 - 并且 sum 函数只能对正元素求和,即使用户也可以输入负元素......

I need to create program - a vector - with n number of elements the user can prescribe - and the sum function can only sum POSITIVE elements even though the user can enter negative elements as well...

在computeSum函数中我还需要为整个组添加一个成功"

In the computeSum function I also need to add a "success" to the whole group

computeSum (dataVec, howMany, total, sucess);

并为输入的人创建一个参数 - 所有负数但想要对它们求和但由于没有正数而无法求和

and create a parameter for people who enter - all negative numbers but want to sum them but are unable to because there are no positive numbers

if (success) {
   cout << "The sum is " << total << endl;
}
else {
cerr << "Oops, you cannot add these elements.";
}

这就是我得到的

#include <iostream>
#include <vector>        // need this in order to use vectors in the program
using namespace std;

int main()
{
    vector<double> dataVec;

    double i, n, howMany, total;
    cout << "How many numbers would you like to put into the vector?";
    cin >> n;

    dataVec.resize(n);

    for(vector<double>::size_type i=0;i < n;i++)
    {
        cout << "Enter the numbers: \n";
        cin >> dataVec[i];
    }

    cout << "How many POSITIVE numbers would you like to sum?";
    cin >> howMany;
    cout << computeSum (dataVec, howMany, total);
}

 double computeSum (vector<double> &Vec, howMany, total)
 {
      double total =0;
      for(int i=0;i < howMany;i++)
    total+=Vec[i];
      return total;
 }

我似乎也无法编译这个 - 在 int main() 中没有理解 computeSum();在 computerSum() 中没有理解 howMany;并且在全局范围内 total() 和 howMany() 未声明(我想这意味着我需要在全局范围内进行 decalre ?)

I also seem to having trouble compiling just this - computeSum() is not being understood in int main(); howMany is not being understood in computerSum(); and on a gloabl scope total() and howMany() are undeclared (I guess that would mean i would need to decalre globally???)

推荐答案

事实上,accumulate 剪掉",用一个合适的只考虑正值的函子:

In fact, accumulate will "cut it", with an appropriate functor that only regards positive values:

int sum_positive(int first, int second) {
    return first + (second > 0 ? second : 0);
}

…

std::accumulate(data.begin(), data.begin() + how_many, 0, sum_positive);

这篇关于创建一个求和函数,仅对向量的一部分求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-09 01:25