我是编码的初学者,我无法修复此代码,而且我发疯了。它一直告诉我某些变量没有被声明,我不确定如何修复它。
#include <iostream>
using namespace std;
int main()
{
int (a = 0), sum;{
cout << "This program should read all integer numbers ";
cout << "to sum until a negative number is entered\n";
exit(0);
}
while(a < 0) {
cout << "Enter an integer number: ";
cin >> a;
sum += a;
}
cout << "The sum is sum\n";
return 0;
}
答案 0 :(得分:4)
你没有初始化总和,所以它可以从任何值开始。
你无缘无故地拥有额外的无意义{ }
层。
您的最终cout
声明实际上并未打印变量
将其更改为:cout << "The sum is " << sum << "\n";
#include <iostream>
using namespace std;
int main()
{
int a = 0, sum = 0;
cout << "This program should read all integer numbers ";
cout << "to sum until a negative number is entered\n";
do {
cout << "Enter an integer number: ";
cin >> a;
if (a > 0)
{
sum += a;
cout << "The sum is currently: " << sum << "; but this is not yet the final value.\n";
}
} while(a > 0) ;
cout << "The sum is " << sum << "\n";
return 0;
}
答案 1 :(得分:-1)
你的代码有很多陷阱。
我发现并纠正的问题:
此代码有效,请与您的代码进行比较:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int a = 0, sum = 0;
cout << "This program should read all integer numbers ";
cout << "to sum until a negative number is entered\n";
while (a <= 0) {
cout << "Enter an integer number: ";
cin >> a;
sum += a;
}
cout << "The sum is " << sum << "\n";
return 0;
}