c语言实现键盘输入若干学生的成绩,统计并输出最高成绩和最低成绩,当输入负数时循环结束
时间: 2023-03-06 22:14:35 浏览: 337
以下是实现该功能的C语言代码:
```c
#include <stdio.h>
int main() {
int score, max = -1, min = 101; // 初始最大值为-1,最小值为101
while (1) {
printf("请输入学生成绩:");
scanf("%d", &score);
if (score < 0) {
break; // 输入负数时跳出循环
}
if (score > max) {
max = score; // 更新最大值
}
if (score < min) {
min = score; // 更新最小值
}
}
printf("最高成绩为:%d,最低成绩为:%d\n", max, min);
return 0;
}
```
程序中使用 `while` 循环,每次通过 `scanf` 获取用户输入的学生成绩,如果输入的是负数,则跳出循环。在循环中,使用 `if` 语句来更新最大值和最小值。循环结束后,输出最高成绩和最低成绩。
注意,本程序的假设是输入的成绩都在 0 到 100 的范围内,如果输入的成绩可能超出这个范围,需要进行范围判断和处理。
相关问题
从键盘输入若干学生的成绩,统计并输出最高成绩和最低成绩,当输入负数时循环结束
这道题目可以使用while循环语句实现。首先,我们需要从键盘上输入学生成绩n,然后将n的值赋值给max和min。接着,我们需要使用while循环语句,当输入负数时循环结束。在循环中,我们需要将max和min与n做比较,如果n大于max,则将max的值更新为n;如果n小于min,则将min的值更新为n。最后,我们输出最大值和最小值即可。
代码如下所示(C语言):
```
#include <stdio.h>
int main() {
int n, max, min;
printf("输入学生成绩n:");
scanf("%d", &n);
max = n;
min = n;
while (n >= 0) {
if (n > max) max = n;
if (n < min) min = n;
printf("输入学生成绩n:");
scanf("%d", &n);
}
printf("最大为:%d,最小为:%d", max, min);
return 0;
}
```
c语言从键盘输入若干个学生成绩,统计并输出最高成绩,当输入负数时结束。
可以使用一个变量来保存最高成绩,每次输入一个成绩时,与最高成绩进行比较,如果大于最高成绩,则更新最高成绩。当输入负数时,结束输入并输出最高成绩。
以下是一份示例代码:
```c
#include <stdio.h>
int main() {
int score, max_score = -1; // 初始化最高成绩为-1
printf("请输入学生成绩:\n");
while (1) {
scanf("%d", &score);
if (score < 0) {
break; // 输入负数,结束循环
}
if (score > max_score) {
max_score = score; // 更新最高成绩
}
}
printf("最高成绩为:%d\n", max_score);
return 0;
}
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![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)
![](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)