0

上次看到我之前的帖子的人很抱歉。它充斥着粗心的错误和错别字。这是我的任务:

“编写一个程序,使用户能够通过输入语句输入一系列非负数。在输入过程结束时,程序将显示:奇数个数及其平均值;偶数个数“

这是我的代码:

#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;
}

它似乎工作正常,但是当我输入一个负数来终止程序时,它会将它与其余的平均数一起包含在内。有什么建议可以解决这个问题吗?我知道这是可能的,但我没有想到这个想法。

4

3 回答 3

2

你的主循环应该是这样的:

#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
}
于 2012-10-29T00:38:51.690 回答
1

在这里之后:

cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;

立即检查数字是否为负数

if(number < 0) break;

现在您不需要使用 do-while 循环来检查数字是否为负数。因此,您可以使用无限循环:

while(true) {
   cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
   cin >> number;

   if(number < 0) break;

   // The rest of the code...
}

附加:您的代码有问题。您没有向用户显示偶数和奇数的数量以及输入的数字总数。

另一个附加:您应该使用更有意义的变量名称:

int totalNumEntered = 0, sumEven = 0, sumOdd = 0, numEven = 0, numOdd = 0;

当然,我并不限制您使用这些名称。您也可以使用其他类似的名称。

对于整数除法问题:您必须将表达式值转换为正确的类型(在这种情况下,它是float)。您还应该将平均变量的类型更改为float

float avg1 = float(total1) / float(count1);
float avg2 = float(total2) / float(count2);
于 2012-10-29T00:38:36.837 回答
0

在 cin >> number 之后,立即检查 < 0,如果是则中断。尝试逐行逐步执行程序,以了解执行流程。祝您学习愉快,祝您好运!

于 2012-10-29T00:39:08.397 回答