为什么我不能做简单的数学运算
why cant i get the simple math to work?
它一直给我test1/5作为平均分数,我不知道哪里出了问题。我试过用不同的方式分组(),还有各种各样的东西。我发誓有几次成功了,然后就放弃了。现在已经快凌晨1点了,我还在努力弄清楚这段简单的代码。
例如:60,50,80,70,80给我的平均值是12 (test1/5)
#include <iostream>
#include <string>
using namespace std;
double testAvgCal(double, double, double, double, double, double&);
void printing(double);
int main()
{
double test1 = 0;
double test2 = 0;
double test3 = 0;
double test4 = 0;
double test5 = 0;
double testAvg = 0;
cout << "Enter five test scores separated by commas: " << endl;
cin >> test1 >> test2 >> test3 >> test4 >> test5;
testAvgCal(test1, test2, test3, test4, test5, testAvg);
printing(testAvg);
}
double testAvgCal(double test1, double test2, double test3, double test4, double test5, double& testAvg)
{
testAvg = (test1 + test2 + test3 + test4 + test5)/ 5;
return testAvg;
}
void printing(double testAvg)
{
cout << "The test score average of this student is: " << testAvg << endl;
}
你的问题是:
cout << "Enter five test scores separated by commas: " << endl;
cin >> test1 >> test2 >> test3 >> test4 >> test5;
代码不读取逗号。输入运算符>>
在空格上分隔。
这意味着输入读取第一个数字,然后期望另一个数字,但看到逗号而失败,不读取任何其他内容。
因此,简单的解决方案实际上是改变指令输出:cout << "Enter five test scores separated by space: " << endl;
// ^^^^^
// Changed here
Joachim Pileborg的答案正确地诊断了问题,并提供了一个解决问题的方法。如果您决定保持输入以逗号分隔,您可以使用:
char dummy;
cout << "Enter five test scores separated by commas: " << endl;
cin >> test1 >> dummy >> test2 >> dummy >> test3 >> dummy >> test4 >> dummy >> test5;
以上答案是正确的,
cin>> test1 >> test2 >> test3 >> test4 >> test5;
将不读取逗号,并且需要空格来输入下一个值。
上述建议的另一个解决方案:
double total = 0;
double testScore;
int totalNuberOfTests = 5; //can be changed to whatever you want
for (int i = 0; i< totalNuberOfTests ; i++)
{
cout<<"Eneter score for Test # "<<i+1<<": ";
cin>>testScore;
total += testScore;
}
double testAverage = total/totalNuberOfTests;
相关文章:
- 在c++中用vector填充一个简单的动态数组
- 使用C++中的模板和运算符重载执行矩阵运算
- (C++)分析树以计算返回错误值的简单算术表达式
- 我的简单if-else语句是如何无法访问的代码
- 使用简单类型列表实现的指数编译时间.为什么
- GCC本机矩阵运算库
- 如何在BST的这个简单递归实现中消除警告
- 一种在C++中读取TXT配置文件的简单方法
- 关于简单C++函数(is_palindrome)的逻辑的问题
- 显示错误输出的简单数组排序程序
- 位阵列上的快速AND运算
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 字符串中int的加法运算
- 退出简单while循环时出现问题
- 如何在特征中对二维数组的列执行简单的算术运算
- 在代码中返回3221225725以进行简单概率运算
- 在C++中对二维数组进行快速简单的矩阵运算
- 对字符串副本执行迭代器运算的更简单方法
- 为什么我不能做简单的数学运算
- OpenCV 矩阵运算是否比简单的循环迭代更快?