C语言用结构体输入三个学生信息
时间: 2024-02-28 08:25:23 浏览: 51
可以使用如下的C语言代码定义一个学生的结构体,并使用结构体数组来存储多个学生的信息:
```
#include <stdio.h>
// 定义学生结构体
struct student {
char name[20];
int age;
float score;
};
int main() {
// 定义结构体数组
struct student stu[3];
// 输入三个学生的信息
for (int i = 0; i < 3; i++) {
printf("请输入第%d个学生的姓名、年龄、成绩:", i+1);
scanf("%s %d %f", stu[i].name, &stu[i].age, &stu[i].score);
}
// 输出学生信息
for (int i = 0; i < 3; i++) {
printf("第%d个学生的信息:\n", i+1);
printf("姓名:%s\n", stu[i].name);
printf("年龄:%d\n", stu[i].age);
printf("成绩:%.2f\n", stu[i].score);
}
return 0;
}
```
运行程序后,你可以依次输入三个学生的姓名、年龄、成绩,程序会自动存储这些信息,并输出每个学生的信息。
相关问题
用结构体输入学生信息,c语言
以下是一个用结构体输入学生信息的示例代码:
```c
#include <stdio.h>
struct Student {
char name[20];
int age;
float score;
};
int main() {
struct Student stu;
printf("请输入学生姓名:");
scanf("%s", stu.name);
printf("请输入学生年龄:");
scanf("%d", &stu.age);
printf("请输入学生成绩:");
scanf("%f", &stu.score);
printf("学生信息如下:\n");
printf("姓名:%s\n", stu.name);
printf("年龄:%d\n", stu.age);
printf("成绩:%.2f\n", stu.score);
return 0;
}
```
在这个示例中,我们首先定义了一个名为`Student`的结构体,它包含了学生的姓名、年龄和成绩三个属性。然后在`main`函数中,我们声明了一个名为`stu`的`Student`类型的变量。
接着,我们使用`scanf`函数分别输入学生的姓名、年龄和成绩,并保存到`stu`变量的相应属性中。
最后,我们使用`printf`函数输出学生的信息,其中使用了`stu`变量的各个属性。注意,在输出成绩时使用了`%.2f`格式控制符,保留小数点后两位。
c语言结构体数组输入
你使用循环语句和scanf函数来输入C语言结构体数组。下面是一个示例代码:
#include <stdio.h>
struct student {
int age;
char name[20];
int num;
};
int main() {
struct student s[10]; // 定义结构体数组
for (int i = 0; i < 10; i++) {
printf("请输入第%d个学生的信息:\n", i+1);
printf("年龄:");
scanf("%d", &s[i].age); // 输入年龄
printf("姓名:");
scanf("%s", s[i].name); // 输入姓名
printf("学号:");
scanf("%d", &s[i].num); // 输入学号
}
printf("已输入的学生信息如下:\n");
for (int i = 0; i < 10; i++) {
printf("第%d个学生:\n", i+1);
printf("年龄:%d\n", s[i].age);
printf("姓名:%s\n", s[i].name);
printf("学号:%d\n", s[i].num);
}
return 0;
}
在上述代码中,我们首先定义了一个结构体student,包含了年龄、姓名和学号三个成员。然后在主函数中,我们声明了一个结构体数组s,用来存储多个学生的信息。
接下来,我们使用循环语句和scanf函数来逐个输入每个学生的信息。通过循环变量i来控制输入的次数,从0到9依次代表数组中的每一个元素。在每次循环中,我们使用printf函数提示用户输入相应的信息,然后使用scanf函数将输入的值存储到对应的结构体成员中。
最后,我们使用循环遍历结构体数组,并使用printf函数将每个学生的信息输出到屏幕上。
这样,你就可以使用循环语句和scanf函数来输入C语言结构体数组了。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)