Accelerated C++<3-5>

//编写一个程序用于同时跟踪n个学生的成绩。要求程序能够保持两个向量的同步:第一个应保存学生的姓名;第二个保存总成绩,而这个总成绩能够根据读到的输入来计算。应假定家庭作业成绩的个数是固定的。


Hint

As suggested, use two vectors. Define a maximum number of grades to request for each student. The grades vector will contain that number of grades multiplied by the number of students entered.


Solution

This solution uses two vectors as suggested in the exercise description. The first vector contains the names of each student, and the second vector contains five grades per student. The total number of grades requested for each student is controlled by a constant, max_grades.

This program expects the user to press the enter key after each grade to prevent the program from gathering too many grades. If the user enters more than max_grades numbers on one line, the program will function incorrectly. We will see in later chapters how to avoid this problem.

After the user presses the end-of-file key at the prompt for the next student name, the program will loop through the student_names and student_grades vectors to output each student’s grades and the average of those grades.



#include<iostream>
#include<string>
#include<vector>
using namespace std;


int main(){

const int max_grades=5;

vector<string> student_names;
vector<double> student_grades;

//提示用户输入 
cout<<"please enter the first student's name: ";
string name;
double grade;
int grade_count;
while(cin>>name)
{
cout<<"Enter "<<max_grades<<" grades for "<<name<<": ";
student_names.push_back(name);


grade_count=0;
while(grade_count<max_grades&&cin>>grade)
{
student_grades.push_back(grade);
++grade_count;
}


//根据用户需求,可以输出相应学生数量 
cout<<"please enter the next student's name or end-of-file to exit: ";
}

cout<<endl;
cout<<"**Grades and averages for each student**"<<endl;

typedef vector<string>::size_type name_vec_sz;
name_vec_sz student_count=student_names.size();

typedef vector<double>::size_type grade_vec_sz;
grade_vec_sz grade_index=0;

double grade_total;
for(name_vec_sz student_name_index=0; student_name_index<student_count; ++student_name_index)
{
grade_total=0;

//输出每个学生的信息 
cout<<"Student: "<<student_names[student_name_index]<<endl;
cout<<"Grades: ";

for(grade_count=0; grade_count<max_grades; ++grade_count)
{
//计算每个学生的总成绩 
cout<<student_grades[grade_index]<<" ";
grade_total+=student_grades[grade_index];
++grade_index; 

 
cout<<endl;
cout<<"Average: "<<grade_total/max_grades<<endl;
cout<<endl; 
}
 
return 0;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值