A有一个学生类student,包括学生姓名、成绩,设计一个友元函数,输出成绩对应的等级:大于等于90:优;80~90:良;70~79:中;60!69:及格;小于60:不及格。用C++编写
时间: 2023-06-02 17:04:06 浏览: 69
以下是代码实现:
```c
#include <stdio.h>
typedef struct {
char name[20];
int score;
} Student;
void printGrade(Student stu);
int main(void) {
Student stu1 = {"Alice", 87};
Student stu2 = {"Bob", 55};
printGrade(stu1);
printGrade(stu2);
return 0;
}
void printGrade(Student stu) {
printf("%s的成绩对应等级为:", stu.name);
if (stu.score >= 90) {
printf("优\n");
} else if (stu.score >= 80) {
printf("良\n");
} else if (stu.score >= 70) {
printf("中\n");
} else if (stu.score >= 60) {
printf("及格\n");
} else {
printf("不及格\n");
}
}
```
思路解析:
首先定义了一个 `Student` 结构体,包括学生姓名和成绩。然后定义了一个 `printGrade` 函数,输入一个学生信息,输出相应等级。在 `main` 函数中创建两个学生对象,分别是 Alice 和 Bob,然后依次调用 `printGrade` 函数即可。
值得注意的是,在 `printGrade` 函数中,我们使用了 `if...else if...else` 的条件语句来判断成绩所对应的等级,并输出相应的结果。
相关推荐
![doc](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)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)