C++ 布尔与空问题

C++ 布尔与空问题,c++,C++,下面是我的代码,编辑得稍微多一些,但现在我仍然停留在success参数上: #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 succes

下面是我的代码,编辑得稍微多一些,但现在我仍然停留在success参数上:

#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);
}
#包括
#包括//为了在程序中使用向量,需要这个
使用名称空间std;
无效计算(向量和向量,整数多少,整数总数,布尔成功)
//将向量中的正数求和的computeSum函数
{
成功=真实;
总数=0;
如果(成功){
对于(int j=0;j0){
总+=Vec[j];
}否则{
总+=Vec[j+1];
}
返回总数;
}否则{
欧洲核子研究中心;
dataVec.resize(n);
对于(向量::大小\类型i=0;icoutA
void
返回值表示函数不返回任何内容。如果要返回
total
,则返回类型应为
int

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

<>我会考虑从代码中删除<代码>成功>代码>,不要将代码>总数>代码>传递给函数(如果你要返回它就不必要)C++中的许多向量有一个<代码>大小<代码>方法,它给了向量的大小,并且可以在函数中使用。 还有一件事,结构:

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

这将给出所有正值的总和,完全忽略负值。

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


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

在返回
void
的函数中,您得到了
return total
void
表示该函数不返回任何内容

我认为您希望
return total
更新调用中的
total
参数,但这不是它的工作方式


最好回到第一步,阅读有关值参数和函数结果的内容。

您正在尝试超出您能力范围的内容。请从“Hello World”开始顺便说一下,你也声明<代码>主< /代码>有一个<代码> int <代码>结果,但你永远不会返回任何东西。我猜想编译器也会抱怨这个问题。@丹尼尔:不是在C++(或C99)中。从<代码>结束时,主< <代码> >隐式<代码>返回0;< /C> >。
for each index:
    if vector[index] > 0:
        add vector[index] to total