布尔和Void问题 [英] Boolean and Void problem
问题描述
所以这里是我的代码有点更多的编辑,但现在我坚持的成功参数:
So here is my code a little more edited however now I'm stuck on the success parameter:
#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 - 所以在这种情况下我的return total在if语句中只打印出总计?
- 还说在int main()函数中,成功没有声明 - 我将如何声明它?
When I compile it I get errors like this: - return statement with a value in function returning void - so in that case would my "return total" in the if statement just print out the total? - In also says in the int main() function that success was not declared - how would i go about declaring it?
推荐答案
A void
返回值表示函数不返回任何内容。如果要返回 total
, int
,返回类型应为 int
。
A void
return value means the function doesn't return anything. If you want to return total
, an int
, the return type should be int
.
然后,您需要在使用变量之前声明变量。您的 main
函数没有声明的变量,而且事实上,它似乎是完全不必要的。
And, yes, you need to declare variables before you use them. Your main
function has no success
variable declared and, in fact, it appears to be totally unnecessary anyway.
我会考虑从你的代码中完全删除 success
,而不是通过 total
到函数(如果你要返回它是没有必要的),并摆脱传递的 howMany
- C ++中的向量有一个 size
方法,它给出了向量的大小,你可以在函数中使用它。
I'd consider removing success
totally from your code, not passing total
to the function (it's unnecessary if you're going to return it), and getting rid of the passed-in howMany
- vectors in C++ have a size
method which gives you the size of the vector and you can use that within the function.
还有一件事,构造:
for(int j=0;j < howMany;j++)
if (Vec[j] > 0){
total+=Vec[j];
} else {
total+=Vec[j+1];
}
在元素不为正的情况下,它将添加下一个元素,重复计算,而不考虑其符号。
is not going to behave itself. In cases where an element is not positive, it will add the next element, double counting, and irrespective of its sign.
类似于(伪代码):对于每个索引:
You probably need something like (pseudocode):
for each index:
if vector[index] > 0:
add vector[index] to total
正值,完全忽略底片。
这篇关于布尔和Void问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!