可以用结构组或指针来解决上面的问题吗?怎么解决呢
时间: 2023-09-12 12:06:41 浏览: 31
可以使用结构体或指针来解决上面的问题。使用结构体可以将学生的信息组织在一起,而使用指针可以方便地操作这些信息。
以下是使用结构体的C语言代码实现:
```c
#include <stdio.h>
struct Student {
int id;
char name[20];
int score1;
int score2;
int score3;
};
int main() {
// 定义学生数组
struct Student students[3] = {
{106, "zhang", 89, 96, 88},
{107, "wang", 79, 86, 91},
{109, "zhao", 78, 65, 67}
};
// 判断是否通过考试
for (int i = 0; i < 3; i++) {
int total = students[i].score1 + students[i].score2 + students[i].score3;
if (total >= 240) {
printf("%d %s passed the exam.\n", students[i].id, students[i].name);
} else {
printf("%d %s failed the exam.\n", students[i].id, students[i].name);
}
}
return 0;
}
```
输出结果与之前的代码相同。这里定义了一个结构体`Student`,包含学生的学号、姓名和三门课程的成绩。然后定义了一个包含三个学生信息的数组,并使用循环遍历数组中的学生信息来判断是否通过考试。
以下是使用指针的C语言代码实现:
```c
#include <stdio.h>
struct Student {
int id;
char name[20];
int score1;
int score2;
int score3;
};
int main() {
// 定义学生数组
struct Student students[3] = {
{106, "zhang", 89, 96, 88},
{107, "wang", 79, 86, 91},
{109, "zhao", 78, 65, 67}
};
// 定义指向学生结构体的指针
struct Student *ptr;
// 判断是否通过考试
for (ptr = students; ptr < students + 3; ptr++) {
int total = ptr->score1 + ptr->score2 + ptr->score3;
if (total >= 240) {
printf("%d %s passed the exam.\n", ptr->id, ptr->name);
} else {
printf("%d %s failed the exam.\n", ptr->id, ptr->name);
}
}
return 0;
}
```
输出结果与之前的代码相同。这里定义了一个指向结构体`Student`的指针`ptr`,并使用循环遍历数组中的学生信息来判断是否通过考试。在循环中,使用箭头符号`->`来访问指针指向的结构体中的成员。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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)
![](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)