编写一个读取五个整数并执行一些任务的C++程序
Writing a C++ program that reads five integers and performs a few tasks
我正在尝试制作一个程序,该程序读取五个整数并执行最大值,最小值,平均值,负整数之和以及正整数之和。当前的问题是平均值与正整数的总和相同,其中的总和低于应有的值。示例:我插入了 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 /= counter
将total
除以counter
并将新值设置为total
。
相关文章:
- 如何创建线程序列以按照启动顺序执行任务?
- 编写一个读取五个整数并执行一些任务的C++程序
- 命令模式 - 使用"weight"执行任务的命令
- OpenMP 4.5 任务依赖关系和执行顺序
- 使用 UWP 中的 IAsyncOperation 继续执行任务
- 独立子任务执行
- 在iOS设备上执行并发任务时如何设置正确的线程数?
- 如何在执行异步后台任务的C++中构造对象
- 如何为基类构造函数中的每个子类执行特定任务
- std 库中是否有类/模板可以在超出范围时执行任务
- 正在执行 omp 任务的线程数
- 从Windows任务栏执行时ifstream问题
- 在执行后台任务时与Objective-C中的GUI交互
- 任务 ":app:ndkBuild" 执行失败。>进程'Command'完成,退出值为非零 2
- 对相关数据执行任务级并行性
- 如何用c++在Windows主循环中执行任务
- 在析构函数中执行任务
- 线程在QT中执行任务时如何使用GUI
- 如何在Windows系统中以管理员身份透明地执行任务
- 如何告诉c++并发运行时重用前一个线程来执行任务