c语言编写程序,统计班级同学的平均分,输入-1结束。
时间: 2024-05-28 10:08:41 浏览: 27
#include <stdio.h>
int main() {
int score, sum = 0, count = 0;
float average;
printf("请输入同学的分数,输入-1结束:\n");
scanf("%d", &score);
while(score != -1) {
sum += score;
count++;
scanf("%d", &score);
}
if(count == 0) {
printf("没有输入同学的分数!\n");
} else {
average = (float)sum / count;
printf("班级同学的平均分为:%.2f\n", average);
}
return 0;
}
相关问题
在C语言程序中编写七位同学计算平均分的程序
以下是一个简单的 C 语言程序,用于计算七位同学的平均分:
```c
#include <stdio.h>
int main() {
int scores[7];
int sum = 0;
printf("请输入七位同学的成绩:\n");
for (int i = 0; i < 7; i++) {
scanf("%d", &scores[i]);
sum += scores[i];
}
float average = (float)sum / 7;
printf("七位同学的平均分为:%.2f\n", average);
return 0;
}
```
该程序首先定义了一个长度为 7 的整型数组 `scores`,用于存储七位同学的成绩。然后通过 `for` 循环,依次读入每位同学的成绩,并将其累加到变量 `sum` 中。最后,通过除以 7 得到平均分,并输出结果。
注意,该程序没有进行输入验证,如果输入的不是整数,程序可能会出现异常。在实际应用中,应该对输入进行合法性检查。
使用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为止。如果无法打开文件,则会提示无法打开文件并退出程序。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)