【发布时间】:2015-01-19 11:36:04
【问题描述】:
我刚刚制作了一个 c++ 程序来根据用户输入的数字计算平均值,但它总是给出错误的答案,虽然它很简单,但我无法发现问题所在:
#include <iostream>
using namespace std;
void average(void);
char input = 0;
int number = 0;
int mode = 0;
int sum = 0;
int main()
{
cout << "This is a program to calculate the average(mean) of numbers you write. \nPlease enter all the numbers you want to calculate. \nWrite \'q\' after entering numbers to calculate! ^_^" << endl;
average();
return 0;
}
void average(void){
while(input != 'q'){
cin >> input;
sum += input;
number++;
}
mode = (sum / number);
cout << "\aThe mode= " << mode;
}
编辑
我总是得到错误结果的示例:http://i.imgur.com/YxW8Zdp.png
【问题讨论】:
-
由于您使用的是
char变量,因此您是在对每个输入字符的 ASCII 码进行平均,而不是对它们键入的数字进行平均。 -
您必须将“输入”从 char 转换为 int:stackoverflow.com/questions/5029840/…
-
1 秒我会发布我在编辑中得到的内容
-
@vincentp 我需要它 char 来查看用户输入的字母 q int 在这种情况下是否不起作用,并且 sum 必须是 int 因为 sum 可能超过 255,您认为我应该这样做
-
你需要像“sum += charToInt(input);”这样的东西。
标签: c++ average calculator