现有10个学生 声明一个浮点数组 通过随机数给10学生赋值分数 1 找到分数最高的学生序号 2 找到10个学生平均分数 3 数组进行由小到大排序 用C语言写出代码
时间: 2024-09-10 10:08:16 浏览: 37
在C语言中,我们可以使用`<stdio.h>`、`<stdlib.h>`和`<time.h>`头文件来进行随机数生成,以及`<float.h>`处理浮点数。下面是一个简单的示例程序,实现了上述需求:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_OF_STUDENTS 10
void assign_scores(float scores[], int num) {
srand(time(0)); // 设置随机种子,保证每次运行结果不同
for (int i = 0; i < num; i++) {
scores[i] = rand() / (float)(RAND_MAX + 1); // 随机分配[0, 1)之间的浮点数
}
}
void find_highest_score(float scores[], int num, int* highest_index) {
*highest_index = 0;
float max_score = scores[0];
for (int i = 1; i < num; i++) {
if (scores[i] > max_score) {
max_score = scores[i];
*highest_index = i;
}
}
}
float calculate_average(float scores[], int num) {
float sum = 0;
for (int i = 0; i < num; i++) {
sum += scores[i];
}
return sum / num;
}
void sort_scores_descending(float scores[]) {
int i, j;
float temp;
for (i = 0; i < NUM_OF_STUDENTS - 1; i++) {
for (j = 0; j < NUM_OF_STUDENTS - i - 1; j++) {
if (scores[j] < scores[j+1]) {
temp = scores[j];
scores[j] = scores[j+1];
scores[j+1] = temp;
}
}
}
}
int main() {
float student_scores[NUM_OF_STUDENTS];
int highest_score_index;
assign_scores(student_scores, NUM_OF_STUDENTS);
printf("Highest score is assigned to student %d with a score of %.2f\n", find_highest_score(student_scores, NUM_OF_STUDENTS, &highest_score_index), student_scores[highest_score_index]);
float average_score = calculate_average(student_scores, NUM_OF_STUDENTS);
printf("Average score of all students is %.2f\n", average_score);
printf("Scores in descending order:\n");
sort_scores_descending(student_scores);
for (int i = 0; i < NUM_OF_STUDENTS; i++) {
printf("%d: %.2f\n", i+1, student_scores[i]);
}
return 0;
}
```
这个程序首先初始化一个浮点数组,然后分别找到最高分的学生、计算平均分并按降序排序。注意,由于浮点数比较可能存在精度问题,这里假设成绩范围是[0, 1),并且在排序时直接进行了整数比较。
阅读全文