您的位置:首页 > 其它

定义和使用结构体变量---恶补之五

2016-09-22 11:53 183 查看
C语言允许用户建立由不同类型数据组成的组合型的数据结构,它称为结构体(structure)

structrue Student

{ int num;

char name[20];

…………

};

structure 结构体名

{成员列表};(变量名表列)

注:当structrt Student b = {.name=”Zhang Fang”};

其他未被初始化的数值型成员初始化为0,字符型初始化为‘\0’,指针型成员初始化为NULL。

//”.”运算符的优先级最高

例9.2 输入两个学生的学号、姓名和成绩,输出较高成绩学生的信息。

#include<stdio.h>
int main()
{
struct Student
{
int num;
char name[20];
float score;
}student1,student2;
scanf("%d,%s,%f",&student1.num,&student1.name.&student1.score);
scanf("%d,%s,%f",&student2.num,&student2.name.&student2.score);
printf("The higher score is:\n");
if(student1.score>student2.score)
printf("%d,%s,%6.2f",student1.num,student1.name.student1.score);
else if(student2.score>student1.score)
printf("%d,%s,%6.2f",student2.num,student2.name.student2.score);
else {
printf("%d,%s,%6.2f",student1.num,student1.name.student1.score);
printf("%d,%s,%6.2f",student2.num,student2.name.student2.score);
}
return 0;
}


例9.3

有3个候选人,每个选民只能投一票选一人,要求编一个统计投票的程序,先后输入备选人的名字,最后输出各人得票结果。

#include<stdio.h>
struct Person
{
char name[20];
int count;
}leader[3]={"Li",0,"zhang",0,"sun",0};
int main()
{
int i,j;
char leader_name[20];
for(i=0;i<=10<i++)
{
scanf("%s",leader_name);
for(j=0;j<3;j++)
{
if(strcmp(leader_name,leader[j].name)==0)
leader[j].count++;
}
}
printf("\nResult:\n");
for(i=0;i<3;i++)
{
printf("%5s:%d\n",leader[i].name,leader[i].count);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: