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