这是我的任务。
编写一个读取一系列测试成绩的C ++程序。 如果测试分数> = 90 &&,<= 100; 打印字母“ A”。 如果分数> = 80但<90, 打印字母等级“ B”。 如果考试分数> = 70且<80, 打印字母等级“ C”。 如果测试分数> = 60但<70 打印字母“ D”级 如果考试分数<60 打印字母“ F”。 打印分数和相应的成绩。 确定并打印最高分数, 最低分数,平均分数, 和测试次数。 在测试成绩为负数时终止。
我的代码工作正常,但是我觉得有更好的方法来做到这一点。我只是想知道是否有更好或更简单的编码方式。
这是我的代码。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ifstream inFile;
int Score, MaxScore, MinScore, AvgScore, NumTests, TotalScore, Num;
string Grade;
NumTests = 0;
TotalScore = 0;
MaxScore = 0;
MinScore = 100;
inFile.open("indata6.txt");
if (!inFile)
{
cout << "Failed to find inFile." << endl;
return 1;
}
cout << "Test Scores & Grades" << endl;
cout << "--------------------" << endl;
while ( inFile >> Score)
{
NumTests = NumTests + 1;
TotalScore = TotalScore + Score;
if ( Score > MaxScore)
{
MaxScore = Score;
if ( Score >= 90 && Score <= 100)
{
Grade = "A";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 80)
{
Grade = "B";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 70)
{
Grade = "C";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 60)
{
Grade = "D";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 0)
{
Grade = "F";
cout << Score << " " << Grade << endl;
}
else
{
cout << "Invalid Test Score:" << Score << endl;
return 2;
}
}
else if ( Score < MinScore)
{
MinScore = Score;
if ( Score >= 90 && Score <= 100)
{
Grade = "A";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 80)
{
Grade = "B";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 70)
{
Grade = "C";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 60)
{
Grade = "D";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 0)
{
Grade = "F";
cout << Score << " " << Grade << endl;
}
else
{
cout << "Invalid Test Score:" << Score << endl;
return 2;
}
}
else
{
if ( Score >= 90 && Score <= 100)
{
Grade = "A";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 80)
{
Grade = "B";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 70)
{
Grade = "C";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 60)
{
Grade = "D";
cout << Score << " " << Grade << endl;
}
else if ( Score >= 0)
{
Grade = "F";
cout << Score << " " << Grade << endl;
}
else
{
cout << "Invalid Test Score:" << Score << endl;
return 2;
}
}
}
AvgScore = TotalScore / NumTests;
cout << "Max Score: " << MaxScore << endl;
cout << "Min Score: " << MinScore << endl;
cout << "Avg Score: " << AvgScore << endl;
cout << "Number of Tests: " << NumTests << endl;
return 0;
}