布尔和空虚问题

时间:2011-09-19 01:27:39

标签: c++

所以这里是我的代码更多编辑但是现在我坚持成功参数:

#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);
}

当我编译它时,我得到这样的错误: - 返回语句,函数中的值返回void - 所以在这种情况下,if语句中的“return total”会打印出总数吗? - 在int main()函数中也表示未声明成功 - 我将如何声明它?

3 个答案:

答案 0 :(得分:3)

void返回值表示该函数不返回任何内容。如果您想返回total int,则返回类型应为int

而且,是的,您需要在使用它们之前声明变量。您的main函数没有声明success变量,事实上,它似乎完全没有必要。

我会考虑从您的代码中完全删除success,而不是将total传递给函数(如果您要返回它则没有必要),并且删除传入的{ {1}} - C ++中的向量有一个howMany方法,它给出了向量的大小,你可以在函数中使用它。

还有一件事,构造:

size

不会表现自己。如果元素不是正数,它将添加 next 元素,重复计算,并且无论其符号如何。

您可能需要类似(伪代码)的内容:

for(int j=0;j < howMany;j++)
    if (Vec[j] > 0){
        total+=Vec[j];
    } else { 
        total+=Vec[j+1];
    }

这将为您提供所有正值的总和,完全忽略负数。

答案 1 :(得分:1)

你在返回return total的函数中得到voidvoid表示函数不返回任何内容。

您希望return total更新您的通话中的total参数,但这不是它的工作方式。

最好回到原点,阅读价值参数和功能结果。

答案 2 :(得分:0)

错误说明了一切,你试图从返回类型为void的函数返回一个bool。将返回类型更改为void。

关于声明成功,只需将其声明为您声明的所有其他变量。