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

时间:2018-09-26 00:35:46

标签: 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;
}

3 个答案:

答案 0 :(得分: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;
    }

答案 1 :(得分:0)

while循环后,可变计数器的值等于6,因此平均值不正确。用5或counter-1替换它。

 total /= 5;

或者,

total /= (counter-1);

答案 2 :(得分:0)

您使用total作为平均值:

您在这里汇总所有数字:total += num;

在这里您要打印总和而不是平均值:

cout << "The average of all numbers is: " << total << endl;

相反,您的打印行应为:

cout << "The average of all numbers is: " << total /= counter << endl;

为了详细说明,total /= countertotal除以counter并将新值设置为total