2011-09-19 50 views
-1

是我的代码更但是编辑现在我卡在成功参数:布尔虚空问题

#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()函数中说成功没有被声明 - 我将如何去声明它?

+5

你试图超越你的能力。从“Hello World”开始并着手。 – Beta

+0

顺便说一句,你也声明'main'有一个'int'结果,但你永远不会返回任何东西。我怀疑编译器也会对此抱怨。 –

+2

@Daniel:不在C++(或C99)中。落在'main'的末尾会隐含'return 0;'。 –

回答

3

A void返回值表示函数不返回任何内容。如果您想返回total,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]; 
    } 

不会表现自己。在元素不是正数的情况下,它将添加下一个元素,重复计数并且不考虑其符号。

你可能需要像(伪):

for each index: 
    if vector[index] > 0: 
     add vector[index] to total 

这会给你一切积极值的总和,忽略了底片完全。

0

错误说,这一切,你想从一个函数返回类型为void返回一个布尔值。将返回类型更改为void。

关于声明成功,只需声明它像你声明的其他变量。

1

你必须在返回void功能return totalvoid表示该函数不返回任何内容。

如果您希望return total更新呼叫中的参数total,但这不是它的工作方式。

最好回到原点和阅读价值的参数和函数结果。