寻找一些数字中的众数的代码
时间: 2023-04-03 07:02:44 浏览: 168
以下是寻找一些数字中的众数的代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, j, maxCount = 0, mode, count;
printf("请输入数字的个数:");
scanf("%d", &n);
int a[n];
printf("请输入数字:");
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
for(i = 0; i < n; i++)
{
count = 0;
for(j = 0; j < n; j++)
{
if(a[j] == a[i])
{
count++;
}
}
if(count > maxCount)
{
maxCount = count;
mode = a[i];
}
}
printf("众数是:%d\n", mode);
return 0;
}
相关问题
寻找一些数字中的众数,如果存在多个众数,就找众数的平均数的代码
以下是寻找数字中众数的代码:
#include <stdio.h>
int main() {
int n, i, j, count, maxCount = 0, modeCount = 0;
float sum = 0, mode = 0;
printf("请输入数字的个数:");
scanf("%d", &n);
int a[n];
printf("请输入数字:");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
sum += a[i];
}
float mean = sum / n;
for (i = 0; i < n; i++) {
count = 0;
for (j = 0; j < n; j++) {
if (a[j] == a[i]) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
mode = a[i];
modeCount = 1;
} else if (count == maxCount) {
mode += a[i];
modeCount++;
}
}
if (modeCount == 1) {
printf("众数为:%.0f\n", mode);
} else {
printf("众数的平均数为:%.2f\n", mode / modeCount);
}
return 0;
}
注意:以上代码只能找出整数的众数,如果要找出小数的众数,需要进行一些修改。
寻找一些数字中的众数,如果存在多个众数,就找众数的平均数,如果没有众数,就找所有输入数字的平均数的代码
以下是寻找数字中的众数的代码:
#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;
}
希望能够帮到您!
阅读全文