结构变量输入不正确的顺序可能会导致不正确的操作结果
寫一個程序,需求:由...制作3單向動態列表學生數據節點配置,輸入學生數據向每個節點
(每個學生的數據包含學號、全名、成就)。每個節點然后逐個輸出數據。
正確的程序,如下面的:
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)
struct student
{
?int num;
?char name[20];
?float score;
?struct student *next;
} ;
void main()
{
?struct student *head,*p,*q;
?head=p=(struct student*) malloc(LEN);
?scanf("%d,%f,%s",&p->num,&p->score,p->name);
?p=(struct student*) malloc(LEN);
?scanf("%d,%f,%s",&p->num,&p->score,p->name);
?q=(struct student*) malloc(LEN);
?scanf("%d,%f,%s",&q->num,&q->score,q->name);
?head->next=p;
?p->next=q;
q->next=NULL;
?p=head;
?printf("\n結點 1:%d,%5.1f,%s",p->num,p->score,p->name);
?p=p->next;
?printf("\n結點 2:%d,%5.1f,%s",p->num,p->score,p->name);
?q=p->next;
?printf("\n結點 3:%d,%5.1f,%s\n",q->num,q->score,q->name);
}
執行結果為:
輸入:
10101,98,li
10102,87,wang
10103,76,qi
輸出:
結點 1:10101, 98.0,li
結點 2:10102, 87.0,wang
結點 3:10103, 76.0,qi
錯誤的程序例如以下:
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)
struct student
{
?int num;
?char name[2];
?float score;
?struct student *next;
} ;
void main()
{
?struct student *head,*p,*q;
?head=p=(struct student*) malloc(LEN);
?scanf("%d,%s,%f",&p->num,p->name,&p->score);
?p=(struct student*) malloc(LEN);
?scanf("%d,%s,%f",&p->num,p->name,&p->score);
?q=(struct student*) malloc(LEN);
?scanf("%d,%s,%f",&q->num,q->name,&p->score);
?head->next=p;
?p->next=q;
q->next=NULL;
?p=head;
?printf("\n結點 1:%d,%5.1f,%s",p->num,p->score,p->name);
?p=p->next;
?printf("\n結點 2:%d,%5.1f,%s",p->num,p->score,p->name);
?q=p->next;
?printf("\n結點 3:%d,%5.1f,%s\n",q->num,q->score,q->name);
}
執行結果為:
輸入:
10101,wang,,98
10102,wani,,87
10103,wangx,,76
輸出:
結點 1:10101, ?0.0,wang,,98 p�
結點 2:10102, ?0.0,wani,,878p�
結點 3:10103, ?0.0,wangx,,7
想要得到的結果應該為:
結點 1:10101, ?98.0,wang,
結點 2:10102, ?87.0,wani,
結點 3:10103, ?76.0,wangx,
假設將想要輸入的字符串數組放在輸入的中間,就極有可能導致
在輸入完字符串之后,還會將接下來輸入的內容輸入到字符串中,
會導致輸出值發生混亂,得不到想要的結果,因而,最好將字符串
輸入參數放在參數列表的最后,這樣它有可能避免輸出錯誤。
版權聲明:本文博客原創文章。博客,未經同意,不得轉載。
轉載于:https://www.cnblogs.com/lcchuguo/p/4653771.html
總結
以上是生活随笔為你收集整理的结构变量输入不正确的顺序可能会导致不正确的操作结果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: GB35114—②、公共安全视频监控联网
- 下一篇: Python写的一个文件生成器脚本