思维导图
1.定义结构体数组存储5个学生的信息:姓名,年龄,性别。定义函数实现输入,要求形参使用结构体指针。接收函数实现5个学生年龄排序(注意对年龄排序时,交换的是所有信息)。定义函数实现输出,要求形参使用结构体指针接收。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct student{
char name[20];
int age;
char sex[10];
};
void Input(struct student *p,int len);
void Output(struct student *p,int len);
void Age_sort(struct student *p,int len);
int main(int argc, const char *argv[])
{
int n;
printf("请输入学生个数:");
scanf("%d",&n);
struct student arr[n];
struct student *p=arr;
Input(arr,n);
Output(arr,n);
Age_sort(arr,n);
Output(arr,n);
return 0;
}
void Input(struct student *p,int len){
for(int i=0;i<len;i++){
printf("请输入第%d个学生的姓名:",i+1);
scanf("%s",(p+i)->name);
printf("请输入第%d个学生的年龄:",i+1);
scanf("%d",&(p+i)->age);
printf("请输入第%d个学生的性别:",i+1);
scanf("%s",(p+i)->sex);
}
}
void Output(struct student *p,int len){
printf("姓名\t年龄\t性别\n");
for(int i=0;i<len;i++){
printf("%s\t%d\t%s\n",(p+i)->name,(p+i)->age,(p+i)->sex);
}
}
void Age_sort(struct student *p,int len){
for(int i=1;i<len;i++){
for(int j=0;j<len-i;j++){
if((p+j)->age > (p+j+1)->age){
struct student t = *(p+j);
*(p+j)=*(p+j+1);
*(p+j+1)=t;
}
}
}
}
2.定义车辆a和车辆b,实现交换车的信息:品牌,单价,颜色
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct CAR {
char name[20];
int price;
char colour[10];
};
void Output(struct CAR a);
int main(int argc, const char *argv[])
{
struct CAR a={"宝马",111,"白色"};
struct CAR b={"奔驰",222,"黑色"};
Output(a);
Output(b);
struct CAR t=a;
a=b;
b=t;
Output(a);
Output(b);
return 0;
}
void Output(struct CAR a){
printf("品牌\t单价\t颜色\n");
printf("%s\t%d\t%s\n",a.name,a.price,a.colour);
}