用C语言编写程序: 从键盘上输入若干学生的成绩,以-1作为结束标志,统计并输出其中的最高成绩及平均成绩
时间: 2024-06-13 21:03:41 浏览: 30
这个问题可以通过以下步骤解决:
1. 定义变量,包括成绩变量、计数器变量、总成绩变量、最高成绩变量。
2. 使用while循环,输入学生的成绩,每输入一个成绩,就将其加到总成绩变量中,并将计数器变量加1。
3. 在循环中,判断输入的成绩是否大于最高成绩变量,如果是,则将其赋值给最高成绩变量。
4. 当输入-1时,跳出循环,计算平均成绩。
5. 输出最高成绩和平均成绩。
下面是代码实现:
```
#include <stdio.h>
int main() {
float score, total = 0, avg;
int count = 0, max = 0;
printf("请输入学生成绩:\n");
scanf("%f", &score);
while (score >= 0) {
total += score;
count++;
if (score > max) {
max = score;
}
scanf("%f", &score);
}
if (count > 0) {
avg = total / count;
printf("最高成绩为:%d\n平均成绩为:%.2f\n", max, avg);
} else {
printf("没有输入成绩!\n");
}
return 0;
}
```
相关问题
我要一段c语言程序,它能实现从键盘输入若干个学生的成绩,-1 作为结束标志,求出平均 成绩及最高成绩并输出其结果。
好的,以下是能实现你的需求的 C 语言程序:
```c
#include <stdio.h>
int main() {
int score, max = 0, sum = 0, count = 0;
while (1) {
printf("请输入第 %d 个学生的成绩(输入 -1 结束):", count + 1);
scanf("%d", &score);
if (score == -1) break;
sum += score;
count++;
if (score > max) max = score;
}
printf("学生数:%d\n", count);
printf("平均分:%f\n", (float) sum / count);
printf("最高分:%d\n", max);
return 0;
}
```
请注意,本程序不进行输入检查,输入非整数可能导致程序出错。
使用c语言编写程序:从键盘输入若干实数,将实数写入文件,以特殊数值-1 结束
好的,以下是使用 C 语言编写的程序,可以从键盘输入若干实数,将实数写入文件,并以特殊数值-1结束:
```c
#include <stdio.h>
int main() {
float num;
FILE *file;
file = fopen("numbers.txt", "w");
if (file == NULL) {
printf("无法打开文件!");
return 0;
}
while (1) {
printf("请输入实数(输入-1结束):");
scanf("%f", &num);
if (num == -1) {
fprintf(file, "%f", num);
break;
}
fprintf(file, "%f\n", num);
}
fclose(file);
return 0;
}
```
这段代码会先要求您输入实数,然后将其写入文件中,直到输入-1为止。如果无法打开文件,则会提示无法打开文件并退出程序。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)