我目前正在学习使用网页程序编写 C++ 代码,我正在那里学习类(class)。现在最近我得到了以下练习:
Using a while or a do-while loop, make a program that asks the user to enter numbers and keeps adding them together until the user enters the number 0.
我写了下面的代码,希望它能结束练习:
#include <iostream>
using namespace std;
int main(void){
int sum = 0;
int number;
do
{
cout <<endl;
cin >> number;
sum += number;
cout << "The total so far is: " << sum << endl;
} while (number != 0);
cout << "The total is: " << sum << endl;
}
然而,当我运行代码时,我从网站上得到了以下反馈(有两个链接,一个在左边,另一个在右边):
Instructions of the exercise and Webpage feedback on the exercise
你能告诉我我做错了什么吗,或者你能提出一个替代解决方案然后我提供的代码吗?感谢您的任何反馈!
最佳答案
工作代码是:
#include <iostream>
using namespace std;
int main(){
int sum = 0, numbers;
do{
cout << "The total so far is: " << sum << endl;
cin >> numbers;
cout<< "Number: "<< numbers;
sum += numbers;
} while (numbers != 0);
cout << "The total is: " << sum << endl;
return 0;
}
cout>>endl; 行有误。此外,输出应与说明相符。这就是您的回答“错误”的原因。
关于C++ 在循环练习中添加数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33867152/