【发布时间】:2016-04-09 03:11:43
【问题描述】:
所以我正在努力从文件中读取文本(逐行)并输出ID,ID 之后的平均 4 个等级,以及字母等级。因此,任何平均成绩为 50 或以上的字母等级为 S,任何低于 50 的字母为 U,而 2 个免责课程的字母等级为 I。 (如果超过或等于 2,则没有 S 或 U)。
假设文件有数字:
42 50 51 57 52
48 90 -1 60 -1
40 46 -1 59 45
47 50 -1 49 50
输出应该是这样的:
ID=42 Avg=52.5 Grade=S
ID=48 Excused=2 Grade=I
ID=40 Avg=50.0 Grade=S
ID=47 Avg=49.7 Grade=U
类型的等级数
S U I
2 1 1
This is the output I am receiving from my code
它正在读取所有数字,但我需要它来读取第一个数字为ID,然后读取 4 个数字作为等级。
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream in;
ofstream results;
string filename;
char grade;
int S = 0, U = 0, I = 0, i = 0, ID, excused = 0, avg;
double allscores = 0;
cout << "Enter the name of the file that has the scores of students: " << endl;
cin >> filename;
cout << "Enter the number of scores for each student: " << endl;
cin >> ID;
in.open(filename);
results.open("results.txt");
if (in)
{
while (in >> ID)
{
int first = 0
for (i = 0; i<=4; i++)
{
if (first == -1)
excused++;
else
allscores += first;
}
if (first > 4)
{
avg = allscores / (4 - excused);
if (avg >= 50.0)
{
grade = 'S';
S++;
cout << "ID=" << ID << " Avg=" << avg << " Grade =" << grade << endl;
}
else
{
grade = 'U';
U++;
cout << "ID=" << ID << " Avg=" << avg << " Grade =" << grade << endl;
}
}
else
{
grade = 'I';
I++;
cout << "ID=" << ID << " Excused=" << excused << " Grade =" << grade << endl;
}
}
}
else
{
cout << "Couldn't open file\n";
}
cout << "Number of Grades of Type" << endl;
cout << "S " << "U " << "I" << endl;
cout << S << " " << U << " " << I << endl;
in.close();
results.close();
system("pause");
return 0;
}
【问题讨论】:
-
你只是在读 ID 而不是其余的数字
-
我能做些什么来解决这个问题?我对整个文件很陌生...我应该添加另一个 else 语句吗?
-
原谅是什么意思?
-
先做什么?您实际上是如何计算平均值的?
标签: c++ file loops if-statement while-loop