动态链表初试

来源:互联网 发布:美国超级计算机和知乎 编辑:程序博客网 时间:2024/05/22 08:24

/* 
* 程序的版权和版本声明部分: 
* Copyright (c) 2013, 烟台大学计算机学院 
* All rights reserved. 
* 文件名称:test.cpp 
* 作    者:李果
* 完成日期:2013 年 4月 8 日 
* 版 本 号:v1.0 
* 对任务及求解方法的描述部分:
* 输入描述:无 
* 问题描述:
* 程序输出:
输出所有总分高于平均总分且没有挂科的同学的学号、姓名、总分。

* 问题分析:略
* 算法设计:略 
*/ 

//第二周项目4

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

struct Student 
 { 
     char num[14];
  char name[10];
     int cpp; 
     int math; 
     int english; 
  int score;
  struct Student *next;
 };

void print(Student *head,float avg);
int allscore=0;//总学分
float avg;//平均分
int main()
{
 
 ifstream infile("score.dat",ios::in);
 if(!infile)
 {
  cerr<<"打开失败!"<<endl;
  exit(1);
 }

    Student stu[180];
 Student *head,*p1,*p2;
for(int i=0;i<180;i++)
 {
  infile>>stu[i].num>>stu[i].name>>stu[i].cpp>>stu[i].math>>stu[i].english;
  //cout<<stu[i].num<<stu[i].name<<endl;测试的是可以输出学号姓名的。
        stu[i].score=stu[i].cpp+stu[i].math+stu[i].english;
  allscore=allscore+stu[i].score;
  p1=new Student;
  //p1->score=stu[i].score;//只是这一属性赋值了,其他属性都没有赋值,所以输出函数时会出错
  //p1=stu[i];这样不行的额
        //p1->num=stu[i].num;还是不行的,字符要用拷贝函数strcpy(),不可用于string类型;
        strcpy(p1->num,stu[i].num);
  strcpy(p1->name,stu[i].name);
        p1->cpp=stu[i].cpp;
        p1->english=stu[i].english;
        p1->math=stu[i].math;
        p1->score=stu[i].score;
  if(i==0)
   head=p1;
  else
   p2->next=p1;
  p2=p1;
  //cout<<p1->score<<endl;//说明是用这个输出函数用错了
 }
    avg=allscore/180;//233
    p2->next=NULL;
    print(head,avg);
 
 infile.close();
 return 0;
}

void print(Student *head,float avg)
{
 cout<<"以下是总成绩高于平均成绩且无挂科科目的学生的"<<endl;
 cout<<"学号"<<"   "<<"姓名"<<"  "<<"总成绩"<<endl;
 Student *p;
 p=head;
 int person=0;//人数
 while(p!=NULL)
 {
  //cout<<p->score<<endl;
  //p++;居然习惯性的写出这个错误
        if(p->score>avg&&p->cpp>60&&p->english>60&&p->math>60)
  {
   cout<<p->num<<"  "<<p->name<<"   "<<p->score<<endl;
   person++;
  }
  p=p->next;
 }
 cout<<"人数为:"<<person<<endl;//测试人数变化
}