是否有一种方法可以在输入负数时平均不包括负数,这是您终止程序的方式

Is there a way to not include a negative number in an average, when entering a negative number is how you terminate the program?

本文关键字:不包括 方式 终止程序 一种 方法 是否 输入      更新时间:2023-10-16

很抱歉上次看到我以前的线程的人。它充满了粗心的错误和错别字。这是我的作业:

"编写一个程序,该程序将使用户能够通过输入语句输入一系列非阴性数字。在输入过程结束时,该程序将显示:奇数数及其平均值;数字;均匀的数字及其平均值;输入的数量总数。启用输入过程以输入负值停止。确保建议用户该结束条件。"

这是我的代码:

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

之后:

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);

cin>>>>编号后,请检查&lt;0,如果是这样,请打破。尝试逐行逐步浏览程序,以感觉到执行流程。学习有趣的学习,祝你好运!