5.7 上机实践习题

    1.定义一个学生信息的结构,并对其进行初始化,最后输出结果。

    【提示】上述题目主要是要求读者了解结构的定义及使用的知识,重点是掌握如何声明、初始化及使用。

    【关键代码】


    01 struct student//定义结构体 02 { 03 char name[20]; 04 int age; 05 float weight; 06 }; 07 //主要代码 08 using namespace std; 09 student stu1={"Ronaldo",30,70. 5}; 10 cout<<"姓名:"name"<<",年龄:"age"<<",体重:"<<weight"<<endl; 11 cout<<stu1.name<<stu1.age<<<<stu1.weight<<endl;

    2.定义共用体info,可以保存学生的年级或者学校的部门,然后根据用户输入的数据进行相应的输出。

    【提示】上述题目主要是要求读者了解共用体的相关知识,重点是掌握共用体的特点及其使用过程。

    【关键代码】


    01 union info//定义共用体info 02 { 03 int grade;//年级,面向学生 04 char department[20];//部门,面向老师 05 }; 06 using namespace std; 07 info personInfo;//声明共用体变量personInfo 08 int ans=-1; 09 cout<<"老师还是学生?(输入0代表学生,1代表老师):"<<endl; 10 cin>>ans; 11 //同一时刻,grade和department中只能有一个被写入 12 if(ans==0) 13 { 14 cout<<"欢迎你,请输入你所在的年级:"<<endl; 15 cin>>personInfo. grade; 16 cout<<"你的年级是:"<<personInfo.grade<<endl; 17 } 18 if(ans==1) 19 { 20 cout<<"欢迎你,请输入你所在的部门:"<<endl; 21 cin>>personInfo. department; 22 cout<<"你的部门名是:"<<personInfo.department<<endl; 23 }

    3.建立一个学生信息链表,接收用户输入的信息,然后根据用户需要查询的数据输出结果。

    【提示】上述题目主要是要求对结构及指针有所了解,重点掌握链表的使用。

    【关键代码】


    01 struct student//定义结构student 02 { 03 char name[20]; 04 int age; 05 student*next;//指向下一个元素的指针 06 }; 07 08 using namespace std; 09 int i=0; 10 int bfound=0; 11 student c={"Kaka",23,NULL};//声明末尾结构变量,指向为NULL 12 student b={"Deco",27,&c};//声明c之前结构变量b,&c为b.next初始化 13 student a={"Terry",30,&b};//申明b之前结构变量a,&b为a.next初始化 14 student*head=&a; 15 student*pointer=head; 16 char name[128]={0}; 17 18 cout<<"请输入学生姓名"<<endl; 19 cin>>name; 20 21 while(pointer!=NULL) 22 { 23 if(strcmp(pointer->name,name)==0) 24 { 25 bfound=1; 26 break; 27 } 28 29 pointer=pointer->next; 30 } 31 32 if(bfound) 33 { 34 cout<<"name"<<pointer->name<<"age"<<pointer->age<<endl; 35 } 36 else 37 { 38 cout<<"no found"<<endl; 39 }