gpt4 book ai didi

c - 可能的模式错误

转载 作者:太空宇宙 更新时间:2023-11-04 04:20:55 24 4
gpt4 key购买 nike

我编写了这个程序来计算数组的均值、中位数和众数。虽然我已经用一些例子进行了测试,但我发现可能有一种情况我已经忘记了,因为我测试过的许多输入都是有效的,但是我的老师正在使用的测试程序给了我一个特定测试的错误,但我没有看到它的输入。也许有人可以看看我是否在代码的模式点处犯了错误:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

void *safeMalloc(int n) {
void *p = malloc(n);
if (p == NULL) {
printf("Error: malloc(%d) failed. Out of memory?\n", n);
exit(EXIT_FAILURE);
}
return p;
}

int main(int argc, char *argv[]) {
int n, i;
scanf("%d", &n);
int *array = safeMalloc(n * sizeof(int));
for (i = 0; i < n; i++) {
int value;
scanf("%d", &value);
array[i] = value;
}

//mean
double mean;
double sum = 0;
for (i = 0; i < n; i++) {
sum = sum + (double)array[i];
}
mean = sum / n;
printf("mean: %.2f\n", mean);

//median

float temp;
int j;
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++) {
if (array[i] > array[j]) {
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
printf("median: %d\n", array[n / 2]);

//mode

int val = array[0], noOfRepetitions = 1, valMax = array[0], maxRepetitions = 1, possibleMax = 1;

for (i = 1; i < n; i++) {
if (array[i] == val) {
noOfRepetitions++;
}

if (array[i] != val) {
val = array[i];
noOfRepetitions = 1;
}

if (noOfRepetitions == possibleMax) {
maxRepetitions = 1;
continue;
}

if (noOfRepetitions > maxRepetitions) {
valMax = val;
maxRepetitions = noOfRepetitions;
possibleMax = maxRepetitions;
}
}

if (maxRepetitions > 1) {
printf("mode: %d\n", valMax);
} else {
printf("mode: NONE\n");
}

return 0;
}

我对模式的想法是因为数字在横向时被排序。如果下一个元素与前一个元素相同,则增加 noOfRepetitions。如果到目前为止 noOfRepetition 大于 maxRepetitions,请替换为它。如果我们有 2 个以上的重复次数相同的数字,还要存储所需的最后一个最大值。

编辑:数组的模式应返回数组中出现次数最多的数字。如果我们有 2 个或更多个具有相同最大出现次数的数字,则该数组上没有模式。

最佳答案

我发现了我的错误。我没有想到当我有相同最大频率的数字,然后是一个频率较低但仍然比其他数字大的情况。例如:1 1 1 2 2 2 3 3 4 5 6。用我的代码,结果应该是 3。我只需要更改 noOfRepetitions 与 oldMaxRepetition 的比较。

关于c - 可能的模式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46904830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com