c++ - 编写一个读取五个整数并执行一些任务的 C++ 程序

标签 c++ function

我正在尝试编写一个程序来读取五个整数并执行最大值、最小值、平均值、负整数和以及正整数和。当前的问题是平均值与正整数之和相同,而正整数之和低于应有的值。示例:我插入了 5、5、5、5、1 个整数。 16 是平均值,16 是所有正整数的总和。

int main()
{
    int min = 0, max = 0, num = 0, counter = 1, pos = 0, neg = 0;
    double total = 0;
    do {
        cout << "Enter in a number: ";
        cin >> num;
        if (num > max)
            max = num;
        if (num < min)
            min = num;
        if (num < 0) {
            neg += num;
        }
        if (num > 0) {
            pos += num;
        }
        total += num;
        counter++;
    } while (counter <= 5);

    total /= counter;
    cout << "Smallest Number of the list is: " << min << endl;
    cout << "Largest Number of the list is: " << max << endl;
    cout << "The sum of negative numbers is: " << neg << endl;
    cout << "The sum of positive numbers is: " << pos << endl;
    cout << "The average of all numbers is: " << total << endl;
    return 0;
}

最佳答案

我已经为您更新了代码。学习使用调试器是一项值得的练习,您可以逐行调试代码来查找问题。这是学习语言并避免数小时痛苦的好方法。

#include <iostream>
#include <climits> // INT_MAX, INT_MIN

using namespace std;
int main()
   {
//make min and max the opposite so the first number entered with replace both
    int min = INT_MAX, max = INT_MIN, num = 0, counter = 0, pos = 0, neg = 0;
    double total = 0;
    do {
        cout << "Enter in a number: ";
        cin >> num;
        if (num > max)
            max = num;
        if (num < min)
            min = num;
        if (num < 0) {
            neg += num;
        }
        if (num > 0) {
            pos += num;
        }
        total += num;
        counter++;
    } while (counter < 5);  // go from 0 to 4, ending with counter == 5
    total /= counter;
    cout << "Smallest Number of the list is: " << min << endl;
    cout << "Largest Number of the list is: " << max << endl;
    cout << "The sum of negative numbers is: " << neg << endl;
    cout << "The sum of positive numbers is: " << pos << endl;
    cout << "The average of all numbers is: " << total << endl;
    return 0;
    }

关于c++ - 编写一个读取五个整数并执行一些任务的 C++ 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52508335/

相关文章:

c++ - DeviceIoControl GetLastError 87 (ERROR_INVALID_PARAMETER)

c++ - 指向相同内存位置的两个指针并删除其中一个

c++ - 如何从同一个类的另一个成员函数中调用仿函数?

mysql - 如何在MySQL表中选择每1000转

c++ - 在 C++ 中的窗口上接收挂起的拖放操作的通知

c# - 在特定窗口上执行 Ctrl-C 而不聚焦它

c++ - C函数调用参数被扰乱

python - 如何使在函数内创建的变量成为全局变量?

c - C 变量声明出现语法错误

c++ - C++ constexpr 函数实际上可以接受非常量表达式作为参数吗?