帮我优化这段代码,并将顾客离队评分完善,用c语言
时间: 2024-02-23 12:01:27 浏览: 19
好的,下面是优化后的代码并完善顾客离队评分的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 定义顾客结构体
typedef struct {
int id; // 顾客编号
int score; // 顾客离队评分
} Customer;
// 生成指定范围内的随机数
int random_int(int min, int max) {
return rand() % (max - min + 1) + min;
}
// 评分函数,返回一个 1~5 的随机整数
int score() {
return random_int(1, 5);
}
int main() {
srand(time(NULL)); // 随机数种子初始化
int n = 10; // 顾客数量
Customer customers[n]; // 创建顾客数组
// 初始化顾客数组
for (int i = 0; i < n; i++) {
customers[i].id = i + 1;
customers[i].score = 0;
}
// 模拟顾客离队评分过程
for (int i = 0; i < n; i++) {
printf("顾客 %d 离队评分:", customers[i].id);
customers[i].score = score();
printf("%d\n", customers[i].score);
}
// 计算顾客离队评分总和
int sum = 0;
for (int i = 0; i < n; i++) {
sum += customers[i].score;
}
// 计算平均评分并输出
double avg = (double)sum / n;
printf("顾客离队评分平均值为 %.2f\n", avg);
return 0;
}
```
这个示例程序中,我们使用了结构体来定义顾客类型。在初始化顾客数组时,我们将每个顾客的编号设置为数组下标加一,将评分初始化为 0。然后,我们通过模拟顾客离队评分的过程,为每个顾客随机生成一个 1~5 的评分。最后,我们计算出所有顾客评分的总和以及平均值,并将平均值输出。
这个示例程序还可以进一步优化,比如可以将顾客数量和评分范围作为命令行参数传入程序,以便更灵活地配置。另外,我们还可以使用更好的随机数生成算法,以避免出现重复的评分。