c++ - 有没有办法在平均值中不包含负数,当输入负数时你如何终止程序?

标签 c++

对于上次看到我之前帖子的人来说,我很抱歉。它充满了粗心的错误和错别字。这是我的任务:

"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/

相关文章:

c++ - 我怎样才能让一个派生类的对象的 "reference"成员成为基类的一个实例?

c++ - 为什么 C++ 为我的动态数组分配如此大的内存空间?

C++ <algorithm> 替换所有不工作的事件

c++ - 查找链表的 "Nth node from the end"

c++ - 当调用原始版本的 DLL Hook 函数时,我得到无限递归

php - OpenSSL C++ 加密问题

c++ - 交叉编译时 CMAKE 缺少 sysroot

c++ - 创建一个开箱即用的可移植、跨平台、开源 C++ GUI 应用程序?

c++ - c++静态库中的导出函数

c++ - 类标志的模板专门化