更新:我正在编写一个找到移动平均线的程序,但似乎无法弄清楚为什么我的代码不起作用。它获取正确的数字,但格式不正确。例如,我的程序输出“ 34”而不是“ 34.00”,我认为使变量类型为“ double”将解决此问题。
程序提示:编写一个输出移动平均值的程序(请参阅:https://en.wikipedia.org/wiki/Moving_average)对于一系列用空格分隔的整数(请注意,移动平均值应四舍五入到百位。但是,如果如果遇到非正数,则应重置平均值并发出换行符;否则,运行平均值应以空格分隔。
输入:34 99 12 19 44
预期输出:34.00 66.50 48.33 41.00 41.60
我的输出:34 66.5 48.3333 41 41.6
我的代码:
#include <iostream>
using std::cin; using std::cout; using std::endl;
double input;
double count = 0;
double sum;
double avg;
double prev = 0;
int main(){
while (cin >> input){
if (input == 0 || input < 0)
count = 0;
else
count++;
sum = input + prev;
prev = sum;
avg = sum / count;
cout << avg << ' ';
}
}
您正在使事情变得复杂,您不需要所有的算术运算:
using std::cin; using std::cout; using std::endl;
double input;
double count = 0;
double sum;
int main(){
while (cin >> input){
if (input > 0) {
count++;
sum += input;
cout << (sum / count) << " ";
}
else{
count = sum = 0;
}
}
}