C++课程成绩计算程序中while循环的放置位置咨询
编程需求翻译
在一门英语课程中,每位学生需完成4次学期测验(每次满分50分)和1次期末考试(满分100分)。每次学期测验占课程总成绩的20%,期末考试同样占20%。需编写程序读取4次学期测验成绩及期末考试成绩,计算并输出最终总成绩与对应等级。评分标准为:A(75-100)、B(60-74)、C(50-59)、F(低于50)。
现有代码
#include<iostream> #include<fstream> using namespace std; int main(){ ifstream infile("input.txt"); if (infile.is_open()) cout<<"File is opened"<<endl; else{ cout<<"Unable to open file"<<endl; exit (1); } int id, test1, test2, test3, test4, final1; infile>>id>>test1>>test2>>test3>>test4>>final1; float tests, finals, grade; tests = ((test1+test2+test3+test4)/200.0)*80; finals= (final1/100.0)*20; grade= tests+finals; cout<<"ID"<<"\t"<<"%"<<"\t"<<"Grade"<<endl; if(grade>=75) cout<<id<<"\t"<<grade<<"\t"<<"A"<<endl; else if(grade>=60) cout<<id<<"\t"<<grade<<"\t"<<"B"<<endl; else if(grade>=50) cout<<id<<"\t"<<grade<<"\t"<<"C"<<endl; else cout<<id<<"\t"<<grade<<"\t"<<"F"<<endl; infile>>id>>test1>> test2>>test3>>test4>>final1; infile.close(); }
技术问询
当前上述代码仅能处理一组学生数据,现需添加while循环以支持批量读取并处理多组学生成绩数据,请问应将while循环放置在该程序的哪个位置?
解决方案
你需要把while循环放在读取学生数据、计算成绩、输出结果的代码块外层,同时调整表头输出位置避免重复打印。具体实现如下:
- 将表头
cout<<"ID"<<"\t"<<"%"<<"\t"<<"Grade"<<endl;移到循环外部,确保只打印一次。 - 用
infile >> id >> test1 >> test2 >> test3 >> test4 >> final1作为循环条件——当文件能成功读取一组完整的学生数据时,进入循环处理该组数据;读取失败(文件结束)时自动退出循环。
修改后的完整代码:
#include<iostream> #include<fstream> using namespace std; int main(){ ifstream infile("input.txt"); if (infile.is_open()) cout<<"File is opened"<<endl; else{ cout<<"Unable to open file"<<endl; exit (1); } // 表头仅打印一次 cout<<"ID"<<"\t"<<"%"<<"\t"<<"Grade"<<endl; int id, test1, test2, test3, test4, final1; // 循环读取并处理每组学生数据 while (infile >> id >> test1 >> test2 >> test3 >> test4 >> final1) { float tests, finals, grade; tests = ((test1 + test2 + test3 + test4) / 200.0) * 80; finals = (final1 / 100.0) * 20; grade = tests + finals; if(grade>=75) cout<<id<<"\t"<<grade<<"\t"<<"A"<<endl; else if(grade>=60) cout<<id<<"\t"<<grade<<"\t"<<"B"<<endl; else if(grade>=50) cout<<id<<"\t"<<grade<<"\t"<<"C"<<endl; else cout<<id<<"\t"<<grade<<"\t"<<"F"<<endl; } infile.close(); }
这样修改后,程序会自动遍历input.txt中的所有学生数据,直到文件结束,无需手动处理每组数据。
内容的提问来源于stack exchange,提问作者Cookie
相关产品推荐
相关产品推荐

