我似乎在我的代码中的某个地方陷入无限循环,但我找不到位置。我正在为一个班级做一个作业,要求我平均得分2组学生(2个输入文件)并将结果输出到results.out。我被困在某个地方,需要知道我应该在哪里看下一步。我复制了我的代码和下面的两个输入文件。截至目前,我的results.out文件中没有任何内容。
我的代码:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char courseID1; //Course Letter
char courseID2;
int count = 1,
sum = 0,
sum2 = 0,
k = 0,
score;
ifstream group1; //Input stream for group1
ifstream group2; //Input stream for group2
ofstream results; //Output stream for the results
//Open the input files
group1.open("group1.dat");
group2.open("group2.dat");
//Open the output file
results.open("results.out");
while (count <= 5)
{
//Read the class ID
group1 >> courseID1;
group2 >> courseID2;
sum = 0;
k = 0;
group1 >> score;
while(score != -999)
{
k = k + 1;
sum = sum + score;
}
float avg1 = (float)sum/k;
k = 0;
sum2 = 0;
score = 0;
group2 >> score;
while (score != -999)
{
k = k + 1;
sum = sum + score;
}
float avg2 = (float)sum2/k;
results << "CourseID\tGroup No.\tCourse Average" << endl << endl;
results << courseID1 << "\t1" << avg1;
results << "\t\t2" << avg2 << endl << endl;
count++;
}
return 0;
} //end of main
group1.dat
A 80 100 50 10 32 90 89 100 23 50 -999
B 80 90 80 94 90 34 23 63 23 80 90 -999
C 10 30 20 10 90 50 89 23 90 68 90 10 60 90 73 35 90 -999
D 34 80 45 89 90 n23 90 12 34 90 84 100 90 59 -999
E 100 83 93 20 63 -999
group2.dat
A 20 75 40 25 80 89 100 60 -999
B 80 50 70 19 10 18 80 90 90 26 -999
C 100 30 20 40 90 50 18 90 90 45 90 80 70 30 35 40 -999
D 80 85 45 92 10 90 24 90 23 65 72 90 34 100 -999
E 95 100 88 98 69 -999
以下是输出结果:
courseID Group No. Course Average
A 1 80.50
2 82.75
B 1 78.00
2 75.35
编辑:
我现在在将while循环更改为
后得到此结果while( (group >> score) && score != -999)
我的result.out看起来像这样:
CourseID Group No. Course Average
A 162.4 20
CourseID Group No. Course Average
B 167.9091 20
CourseID Group No. Course Average
C 154.5882 20
CourseID Group No. Course Average
D 167.6 20
CourseID Group No. Course Average
D 1-NaN 20
我该如何解决这个问题?
答案 0 :(得分:1)
你的声明:
while (score != -999){
k = k + 1;
sum = sum + score;
}
你永远不会修改'得分'的值,从而创造一个无限循环。
答案 1 :(得分:0)
while (score != -999)
{
k = k + 1;
sum = sum + score;
}
你陷入了这个循环。该循环仅在score == -999
时退出,并且您不会在此循环中的任何位置修改score
的值。
始终使用调试器。您很快就会找到程序卡住的位置。
答案 2 :(得分:0)
您应该在关闭括号之前在循环内添加group1 >> score
。像这样:
group1 >> score;
while(score != -999)
{
k = k + 1;
sum = sum + score;
group1 >> score;
}
第二个循环
也是如此这看起来更好:
while( (group >> score) && score != -999 )
{
k = k + 1;
sum = sum + score;
}
答案 3 :(得分:0)
我想,就像这样:
do
{
group1 >> score;
k = k + 1;
sum = sum + score;
} while (score != -999);