【发布时间】:2019-04-14 05:44:10
【问题描述】:
我正在尝试根据使用给出的数据文件给出的分数来计算班级的平均值。
我使用的公式是grade_Average = sum / i;
给出的数据文件是:
Joe Johnson 89
Susie Caldwell 67
Matt Baker 100
Alex Anderson 87
Perry Dixon 55
我得到的输出是
Johnson,Joe B
Caldwell,Susie D
Baker,Matt A
Anderson,Alex B
Dixon,Perry F
班级平均成绩
我不确定我的公式是否错误,或者公式是否放错地方。
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
// Variable declarations:
string fName[10];
string lName[10];
float grade_Average;
string file;
string name;
int scores[10];
float sum = 0;
char grade;
int i = 0;
ifstream din;
// Function body:
cout << "Enter the name of the file. " << endl;
cin >> file;
din.open(file.c_str());
if (!din)
{
cout << " Cannot open the input file. Please try again." << endl;
return 0;
}
cout << setw(10) << setfill(' ') << "Name" <<setw(20)<<setfill(' ')<< "Grade" << endl;
while (!din.eof())
{
din >> fName[i];
din >> lName[i];
din >> scores[i];
sum = sum + scores[i];
switch (static_cast<int> (scores[i]/10))
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
grade = 'F';
break;
case 6:
grade = 'D';
break;
case 7:
grade = 'C';
break;
case 8:
grade = 'B';
break;
case 9:
grade = 'A';
break;
case 10:
grade = 'A';
break;
default:
cout << "Invalid score." << endl;
i++;
}
name = lName[i] + ',' + fName[i];
cout << setw(10) << setfill(' ') << name << setw(20) << setfill(' ')<<(" ") << grade << endl;
}
grade_Average = sum / i;
cout << "Class average " << grade_Average << endl;
din.close();
return 0;
}
【问题讨论】:
-
如果你使用 c++,一定要使用调试器 :)
-
i仅在输入无效分数时才会增加。这意味着如果所有分数都有效,它将具有零值。然后在语句grade_average = sum/i中使用它,其中sum和grade_average的类型为float。使用 IEEE 浮点格式(不保证,但可能是您所拥有的)除以零会导致无穷大。
标签: c++ arrays while-loop