对于上次看到我之前帖子的人来说,我很抱歉。它充满了粗心的错误和错别字。这是我的任务:
"Write a program that will enable the user to enter a series of non-negative numbers via an input statement. At the end of the input process, the program will display: the number of odd numbers and their average; the number of even numbers and their average; the total number of numbers entered. Enable the input process to stop by entering a negative value. Make sure that the user is advised of this ending condition."
这是我的代码:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number, total1=0, total2=0, count1=0, count2=0;
do
{
cout << "Please enter a number. The program will add up the odd and even ones separately, and average them: ";
cin >> number;
if(number % 2 == 0)
{
count1++;
total1+=number;
}
else if (number >= 0)
{
count2++;
total2+=number;
}
}
while (number>=0);
int avg1 = total1/count1;
int avg2 = total2/count2;
cout << "The average of your odd numbers are: " << avg1 << endl;
cout << "The average of your even numbers are " << avg2 << endl;
}
它似乎工作正常,但是当我输入一个负数来终止程序时,它会将它包含在其余的平均数中。有什么建议可以解决这个问题吗?我知道这是可能的,但我没有想到。
最佳答案
你的主循环应该是这样的:
#include <iostream>
for (int n; std::cout << "Enter a number: " && std::cin >> n && n >= 0; )
{
// process n
}
或者,如果您想发出诊断信息:
for (int n; ; )
{
std::cout << "Enter a number: ";
if (!(std::cin >> n)) { std::cout << "Goodbye!\n"; break; }
if (n < 0) { std::cout << "Non-positve number!\n"; break; }
// process n
}
关于c++ - 有没有办法在平均值中不包含负数,当输入负数时你如何终止程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13114560/