用C语言编写代码实现:请输入若干个学生成绩,5到10人,超过范围提示错误信息后,重新输入;每个学生的成绩不能超过100或小于0,超过范围提示错误信息后,重新输入; 统计输出最高分、最低分、平均成绩,标准差,并按成绩输出从高到低排序
时间: 2024-11-12 14:39:39 浏览: 31
在C语言中,我们可以使用数组和循环结构来实现这个功能。这里是一个简单的示例:
```c
#include <stdio.h>
#include <math.h> // 包含用于计算标准差的头文件
#define MAX_STUDENTS 10
// 函数声明
double calculate_average(int scores[], int num_students);
double calculate_std_deviation(int scores[], int num_students);
int main() {
int scores[MAX_STUDENTS];
int num_students = 0;
int score;
printf("请输入学生人数(5到10人): ");
scanf("%d", &num_students);
while (num_students < 5 || num_students > 10) { // 检查输入范围
printf("输入无效! 请重新输入(5到10人): ");
scanf("%d", &num_students);
}
for (int i = 0; i < num_students; ++i) {
printf("请输入第%d位学生的成绩: ", i + 1);
scanf("%d", &score);
if (score < 0 || score > 100) { // 检查成绩范围
printf("错误!成绩应介于0和100之间,请重新输入: ");
continue;
}
scores[i] = score;
}
double max_score = scores[0], min_score = scores[0]; // 初始值
double sum = 0;
for (int i = 0; i < num_students; ++i) {
max_score = (scores[i] > max_score) ? scores[i] : max_score;
min_score = (scores[i] < min_score) ? scores[i] : min_score;
sum += scores[i];
}
double average = calculate_average(scores, num_students);
double std_dev = calculate_std_deviation(scores, num_students);
printf("最高分: %d\n", max_score);
printf("最低分: %d\n", min_score);
printf("平均成绩: %.2f\n", average);
printf("标准差: %.2f\n", std_dev);
// 按成绩从高到低排序并输出
for (int i = 0, j = num_students - 1; i < j; ++i, --j) {
if (scores[i] < scores[j]) {
int temp = scores[i];
scores[i] = scores[j];
scores[j] = temp;
}
}
printf("成绩从高到低排序:\n");
for (int i = 0; i < num_students; ++i) {
printf("%d ", scores[i]);
}
return 0;
}
// 辅助函数:计算平均值和标准差
double calculate_average(int scores[], int num_students) {
return (double)sum / num_students;
}
double calculate_std_deviation(int scores[], int num_students) {
double mean = calculate_average(scores, num_students);
double variance = 0;
for (int i = 0; i < num_students; ++i) {
variance += pow(scores[i] - mean, 2);
}
return sqrt(variance / num_students);
}
```
阅读全文