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

Writing a C++ program that reads five integers and performs a few tasks

本文关键字:执行 任务 C++ 程序 一个 读取 五个 整数      更新时间:2023-10-16

我正在尝试制作一个程序,该程序读取五个整数并执行最大值,最小值,平均值,负整数之和以及正整数之和。当前的问题是平均值与正整数的总和相同,其中的总和低于应有的值。示例:我插入了 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;
}

变量计数器的值在 while 循环后等于 6,因此平均值不正确。将其替换为 5 或计数器 1。

total /= 5;

total /= (counter-1);

您使用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