寻找一些数字中的众数,如果存在多个众数,就找众数的平均数,如果没有众数,就找所有输入数字的平均数的代码
时间: 2023-04-03 09:02:45 浏览: 86
以下是寻找数字中的众数的代码:
#include <stdio.h>
int main() {
int n, i, j, count, maxCount = 0, modeCount = 0;
float sum = 0, modeSum = 0;
float nums[100];
printf("请输入数字的个数:");
scanf("%d", &n);
printf("请输入数字:");
for (i = 0; i < n; i++) {
scanf("%f", &nums[i]);
sum += nums[i];
}
float mean = sum / n;
for (i = 0; i < n; i++) {
count = 0;
for (j = 0; j < n; j++) {
if (nums[j] == nums[i]) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
modeCount = 1;
modeSum = nums[i];
} else if (count == maxCount) {
modeCount++;
modeSum += nums[i];
}
}
if (modeCount == 1) {
printf("众数为:%.2f\n", modeSum / maxCount);
} else {
printf("没有众数,平均数为:%.2f\n", mean);
}
return 0;
}
希望能够帮到您!
阅读全文