2015-11-23 35 views
3

我目前正在学习通过使用网页程序编写C++,在那里我正在做一门课程。现在,最近我得到了下面的练习:C++在循环中添加数字练习

使用一段时间或do-while循环,使一个程序,要求用户输入数字,直到用户输入数字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

你能告诉我什么我做错了,或者你能提出替代解决方案,然后我提供的代码?感谢您的任何反馈!

+3

我想这不期待你用'cout << endl;'引入的额外换行符? – TartanLlama

+0

你也应该打印'。'每个数字之后。 – Tempux

+0

这工作正常在视觉工作室2013 –

回答

2

工作代码为:

#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错误;。另外,输出应该与说明相匹配。这就是为什么你的答案是“错误的”。

+0

http://i.stack.imgur.com/xJoN7.png http://i.stack.imgur.com/kOgw3。png 当我运行这段代码时,我在网页的控制台以及Visual Studio中得到了正确的结果,但由于某种原因,当我提交代码进行测试时,它不打印字符串,从而导致练习不正确。我的假设是错误在于网页。 – Noir

+1

如何不打印'数字'?期望可能是程序在'cout <<“之后停止输入数字:”;'然后在那之后添加'cin >>数字'。使用当前的答案,在''Number:“被打印并且在控制台上得到两次输入:一次作为实际输入并且一次作为'cout <<”结果:Number:“<< numbers; '此外,练习描述和检查器中的预期结果有冲突:描述列出了0的原始和,但未包含在预期输出列中。 – sendaran

0

我猜测网站正在做一个简单的比较检查。

你能删除第一个cout << endl;

因为这是更接近预期的输出。

至于为什么你没有得到“迄今为止的总数”让我难住。

当您在本地运行时,您是否看到“迄今总计”文本?

0

您应该检查用户是否输入一个号码或确保加法运算

1

我想你应该设计完全相同的输出指令的字符。

#include <iostream> 

using namespace std; 

int main(){ 
    int sum = 0, numbers; 
    do{ 
    cin >> numbers; 
    sum += numbers; 
    cout << "The total so far is: " << sum << endl; 
} while (numbers != 0); 

cout << "The total is: " << sum << endl; 
return 0; 
} 
1

至于我,那么我会写程序如下方式

#include <iostream> 

int main() 
{ 
    int sum = 0; 
    int number; 

    std::cout << "Enter a sequence of numbers (0-exit): "; 

    while (std::cin >> number && number != 0) sum += number; 

    std::cout << "The total is: " << sum << std::endl; 
} 

如果需要输出部分和那么你就可以添加更多的输出语句

#include <iostream> 

int main() 
{ 
    int sum = 0; 
    int number; 

    std::cout << "Enter a sequence of numbers (0-exit): "; 

    while (std::cin >> number && number != 0) 
    { 
     std::cout << "The total so far is: " << (sum += number) << std::endl; 
    } 

    std::cout << "\nThe total is: " << sum << std::endl; 
}