注册 登录
编程论坛 C语言论坛

为什么程序运行只能输入一次,循环不能进行到底,求大神指教

F3268724562 发布于 2019-07-30 16:40, 2297 次点击
#include <stdio.h>
#include <stdlib.h>
typedef struct STUDENTINF
{
    char name[20];
    float score;
    struct STUDENTINF *next;
}stu;
//创建链表;
struct stu* creat(int n)
{
    int i;
    stu* head;
    stu* note;
    stu* end;
    head=(stu*)malloc(sizeof(stu));
    head=end=NULL;   
    for(i=1;i<n;i++)
    {
        note=(stu*)malloc(sizeof(stu));
        printf("请输入学生的姓名\n");
        scanf("%s",note->name);
        printf("请输入学生的成绩\n");
        scanf("%d",&note->score);
        end->next=note;
        end=note;
    }
    end->next=NULL;
    return head;     
}
//遍历链表;
void output(stu *head)
{
    stu* note;
    note=head;
    while(note->next!=NULL)
    {
        printf("姓名:%s\n",note->name);
        printf("成绩:%d\n",note->score);
        note=note->next;
    }
    return ;
}
int main()
{   
    struct stu* creat(int n);
    void output(stu *head);
    stu* head;
    int n;
    printf("请输入创建链表的个数\n");
    scanf("%d",&n);
    head=creat(n);
    output(head);
    return 0;
}
2 回复
#2
wufuzhang2019-07-31 09:43
回复 楼主 F3268724562
你的代码问题挺多的,我把修改的地方注释出来了,你仔细看看。

程序代码:

#include <stdio.h>
#include <stdlib.h>
typedef struct STUDENTINF
{
    char name[20];
    float score;
    struct STUDENTINF *next;
}stu;
//创建链表;
struct STUDENTINF* creat(int n)             //这里要用结构体的名称,不能用别名
{
    int i;
    stu* head;
    stu* note;
    stu* end;
    head=(stu*)malloc(sizeof(stu));
    head=end=NULL;   
    for(i=1;i<=n;i++)                        //i从1开始,那么i<=n才是循环了n次
    {
        note=(stu*)malloc(sizeof(stu));
        printf("请输入学生的姓名\n");
        scanf("%s",note->name);
        printf("请输入学生的成绩\n");
        scanf("%f",&note->score);            //score是float类型,用格式符%f
        
        if (i==1) head = note;                //如果第一次循环,要把值赋给head,不然head一直是NULL
        else end->next = note;                //第二次及以后循环,把值赋给end
        end = note;
    }
    end->next = NULL;
    return head;     
}
//遍历链表;
void output(stu *head)
{
    stu* note;
    note = head;
    while(note != NULL)                        //这里是判断note指针是否为NULL,不为NULL就输出该指针所指向的内容
    {
        printf("姓名:%s\n",note->name);
        printf("成绩:%f\n",note->score);    //%f
        note = note->next;
    }
    return ;
}
int main()
{   
    struct STUDENTINF* creat(int n);
    void output(stu *head);
    stu* head;
    int n;
    printf("请输入创建链表的个数\n");
    scanf("%d",&n);
    if (n<1) exit(0);                        //当输入的个数<1,退出程序
    head=creat(n);
    output(head);
    return 0;
}
#3
F32687245622019-07-31 15:43
回复 2楼 wufuzhang
谢谢大神,我明白了。
1