用C语言的for循环统计10名学生的成绩,求总分和平均分
时间: 2024-03-05 16:52:49 浏览: 66
好的,下面是用 C 语言编写的示例代码:
```c
#include <stdio.h>
int main() {
int scores[10]; // 定义存放学生成绩的数组
int sum = 0; // 总分
float average; // 平均分
// 读入每个学生的成绩
for (int i = 0; i < 10; i++) {
printf("请输入第%d个学生的成绩:", i + 1);
scanf("%d", &scores[i]);
sum += scores[i]; // 累加总分
}
// 计算平均分
average = (float)sum / 10;
// 输出总分和平均分
printf("总分:%d\n", sum);
printf("平均分:%.2f\n", average);
return 0;
}
```
在程序运行时,会提示用户输入每个学生的成绩,然后根据 for 循环累加总分,最后计算平均分并输出。注意,这里使用了强制类型转换将 sum 转换为 float 类型,以便计算平均分。输出时使用了格式化字符串 "%.2f",其中的 ".2" 表示保留 2 位小数。
相关问题
用C语言的do whilre循环统计10名学生的成绩,求总分和平均分
好的,我知道了。以下是代码示例:
```c
#include <stdio.h>
int main() {
int i = 1, score, sum = 0;
float avg;
do {
printf("请输入第%d名学生的成绩:", i);
scanf("%d", &score);
sum += score;
i++;
} while (i <= 10);
avg = (float)sum / 10.0;
printf("总分为:%d\n", sum);
printf("平均分为:%.2f\n", avg);
return 0;
}
```
这段代码中,使用了 do-while 循环来输入 10 名学生的成绩,并计算总分和平均分。其中,变量 `i` 用于迭代 10 次循环,变量 `score` 用于输入每个学生的成绩,变量 `sum` 用于累加每个学生的成绩,变量 `avg` 用于存储平均分。最后,使用 `printf` 函数输出总分和平均分。
用c语言输入七个学生的成绩,并计算总分和平均分
下面是用C语言实现输入七个学生的成绩,并计算总分和平均分的代码:
```c
#include <stdio.h>
int main() {
int score[7]; // 存储七个学生的成绩
int total = 0; // 总分
float average; // 平均分
// 输入七个学生的成绩
for (int i = 0; i < 7; i++) {
printf("请输入第%d个学生的成绩: ", i+1);
scanf("%d", &score[i]);
total += score[i]; // 累加总分
}
average = (float)total / 7; // 计算平均分
printf("总分为%d,平均分为%.2f\n", total, average);
return 0;
}
```
在这个程序中,我们定义了一个长度为7的整型数组`score`来存储七个学生的成绩,使用了一个循环来输入每个学生的成绩,并累加总分。注意,我们在计算平均分时需要将总分转换为浮点型,否则计算结果将会是整数类型。
当程序运行时,它会提示用户输入每个学生的成绩,最后输出总分和平均分。