为什么我不能做简单的数学运算

why cant i get the simple math to work?

本文关键字:运算 简单 不能 为什么      更新时间:2023-10-16

它一直给我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;