注册 登录
编程论坛 C++教室

求大神看看哪里错了,运行中断

APTX 发布于 2015-05-18 22:38, 767 次点击
#include <iostream>
#include <stdlib.h>
using namespace std;
class score
{    public:
     int num;
     double Math;
     double English;
     double Programming;
     void inscore(score *head);
     void showscore(score *head);
     double average();
     score *next;
};
void score::inscore(score *head)
{   score *p=0,*q;
    q=new score;
    cout<<"输入学生的学号、数学、英语及程序设计成绩:"<<endl;
    cin>>q->num>>q->Math>>q->English>>q->Programming;
    while( q->num!=0 && q->Math!=0 && q->English!=0 && q->Programming!=0 )
    { if(head==NULL) p=head=q;
      else p->next=q;
      p=q;
      q=new score;
      cout<<"输入学生的学号、数学、英语及程序设计成绩:"<<endl;
      cin>>q->num>>q->Math>>q->English>>q->Programming;
    }
    q->next=NULL;
}
void score::showscore(score *head)
{   cout<<"学号    数学    英语    程序设计    平均成绩:"<<endl;
    while(head)
    {  cout<<head->num<<'\t'<<head->Math<<'\t'<<head->English<<'\t'<<head->Programming<<'\t'<<average()<<endl;
       head=head->next;
    }
    cout<<endl;
}
double score::average()
{   return (Math+English+Programming)/3;
}
int main()
{    score *head=NULL;
     head->inscore(head);
     head->showscore(head);
     return 0;
     system("pause");
}
求改正,最好讲解一下,谢谢

[ 本帖最后由 APTX 于 2015-5-22 11:57 编辑 ]
5 回复
#2
wmf20142015-05-19 05:53
经vc6运行,未出现中断,但没有输出。调试发现你head未取得头链表地址。
#3
APTX2015-05-28 14:26
回复 2楼 wmf2014
要怎么取得呢
#4
诸葛欧阳2015-05-28 16:14
链表的创建和显示没必要放在成员函数里
#5
yangfrancis2015-05-28 21:31
回复 3楼 APTX
因为在你输入链表结点的函数里,head是形参,生命周期只存在于函数体内。要得到头结点,你试一下把保存了头结点的head作为返回值返回出来。另外也可以在函数体外面定义一个head作全局变量,把形参的head去掉不要
#6
yangfrancis2015-05-28 21:33
回复 5楼 yangfrancis
我说错了,不是把head定义成全局变量,是定义成类里面的成员变量
1