这似乎是一个简单的问题,我一直在寻找解决方案或只是其背后的概念,但找不到任何解决方案。
我该如何创建一个循环,该循环要求用户输入任意数量的整数,并且一旦用户键入值99
,循环就会退出并显示循环中所有数字的平均值?
这是我到目前为止所拥有的:
#include <iostream>
#include <string>
using namespace std;
int main () {
// Variables
int numInput;
int numOfIntegers;
bool canContinue;
cout << "Enter the amount of integers you would like to enter: ";
cin >> numOfIntegers;
int oldNums = new int [numOfIntegers];
while (canContinue) {
cout << "Enter a random integer: ";
cin >> numInput;
if (numInput != -1) {
} else {
canContinue = false;
}
}
}
答案 0 :(得分:1)
很简单:
#include <iostream>
#include <string>
using namespace std;
int main () {
int numInput;
int sum = 0;
int cnt = 0;
while (true) {
cout << "Enter a random integer: ";
cin >> numInput;
if (numInput == 99) {
break;
}
sum += numInput;
cnt++;
}
cout << "Average: " << ((double) sum / (double) cnt);
return 0;
}
您不需要将所有单个值保存在数组中。将所有值相加,然后除以计数器就足够了。强制转换为double
可以避免平均精度下降