输入几个数字,找到众数,若众数存在且唯一,则输出众数;若众数存在但不唯一,则输出众数的平均数:若众数不存在,则输出所有输入数字的平均值的代码
时间: 2023-04-02 20:02:43 浏览: 143
以下是代码:
#include <stdio.h>
int main() {
int n, i, j, count, maxCount = , mode = , sum = , numCount = ;
float avg;
printf("请输入数字个数:");
scanf("%d", &n);
int nums[n];
printf("请输入数字:");
for (i = ; i < n; i++) {
scanf("%d", &nums[i]);
sum += nums[i];
}
avg = (float)sum / n;
for (i = ; i < n; i++) {
count = ;
for (j = ; j < n; j++) {
if (nums[j] == nums[i]) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
mode = nums[i];
}
}
for (i = ; i < n; i++) {
if (nums[i] == mode) {
numCount++;
}
}
if (maxCount == 1) {
printf("众数为:%d\n", mode);
} else if (maxCount > 1) {
printf("众数的平均数为:%.2f\n", (float)(mode * numCount) / maxCount);
} else {
printf("所有输入数字的平均值为:%.2f\n", avg);
}
return ;
}
阅读全文