所以这是我的代码,稍微编辑了一下,但现在我陷入了成功参数:
#include <iostream>
#include <vector> // need this in order to use vectors in the program
using namespace std;
void computeSum (vector<int> &Vec, int howMany, int total, bool success)
//the computeSum function that will sum positive numbers in a vector
{
success = true;
total=0;
if (success){
for(int j=0;j < howMany;j++)
if (Vec[j] > 0){
total+=Vec[j];
} else {
total+=Vec[j+1];
}
return total;
} else {
cerr << "Oops! Appears you cannot add up these numbers!";
}
}
int main()
{
vector<int> dataVec;
int i, n, howMany, total;
cout << "How many numbers would you like to put into the vector? \n";
cin >> n;
dataVec.resize(n);
for(vector<int>::size_type i=0;i < n;i++)
{
cout << "Enter your number for " << i+1 << ": \n";
cin >> dataVec[i];
}
cout << "How many POSITIVE numbers would you like to sum? \n";
cin >> howMany;
cout << "Your total is: \n" << computeSum (dataVec, howMany, total, success);
}
当我编译它时,我收到如下错误:
- return 语句,函数中的值返回 void - 那么在这种情况下,if 语句中的“返回总计”是否会打印出总计?
- 在 int main() 函数中还说未声明成功 - 我将如何声明它?
A void
返回值意味着该函数不返回任何内容。如果你想返回total
, an int
,返回类型应该是int
.
是的,您需要在使用变量之前声明它们。你的main
函数没有success
声明了变量,事实上,无论如何,它似乎完全没有必要。
我会考虑删除success
完全来自你的代码,没有通过total
到函数(如果你要返回它,这是不必要的),并摆脱传入的howMany
- C++ 中的向量有一个size
方法给你向量的大小,你可以在函数中使用它。
而且,还有一件事,构造:
for(int j=0;j < howMany;j++)
if (Vec[j] > 0){
total+=Vec[j];
} else {
total+=Vec[j+1];
}
不会表现自己。如果元素不为正,则会添加next元素,重复计算,且不考虑其符号。
您可能需要类似的东西(伪代码):
for each index:
if vector[index] > 0:
add vector[index] to total
这将为您提供所有正值的总和,完全忽略负值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)