C++ 在循环练习中添加数字

标签 c++ loops

我目前正在学习使用网页程序编写 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/

相关文章:

c++ - 在容器之间 move 一系列元素?

java - 将消息从 java 发送到 c++,在 c++ 客户端中收到奇怪的东西

c++ - 这个简单的 Message 类是否证明使用智能指针是合理的?

javascript - 计算 Javascript 数组中条纹的最佳方法是什么?

c++ - 如何迭代位图像素

python - 检查两个给定列表中的一个是否是另一个的循环排列

java - Android GridView 滚动循环

java - 如何在按下按钮时持续循环播放声音并在释放时停止?

Java - 循环被执行,但 header 不符合条件

c++ - 无法输出到 C++ 中的二进制文件