我有此作业分配,用户将输入10个数字并找到这10个数字的模式。我有一种模式工作,我的问题是我不知道如何开始在数组中找到多种模式。前任。1 1 2 2 3 4 5 6 7 8阵列的模式为1,2
这是模式的代码
void displayMode(int numArray[])
{
int countArray[MAX];
int modeCount = 0;
int modeNumber;
int i = 0;
int j = 0;
for(i=0; i < MAX; i++)
{
countArray[i] = 0;
}
for(i=0; i < MAX; i++)
{
for (j = 0; j < MAX; j++)
{
if (numArray[i] == numArray[j])
countArray[i]++;
}
}
for (i=0; i < MAX; i++)
{
if (countArray[i] > modeCount)
{
modeCount = countArray[i];
modeNumber = numArray[i];
}
}
if (modeCount > 1)
printf("nThe mode of the array is: %d",modeNumber);
else
printf("nThe mode of the array is: None");
}
您需要使用具有大小的容器。std::vector
在C 中很容易实现,但是无论如何,这是c。
使用ModeNumbers而不是一个,并为大小创建一个变量:
int modeNumbers[MAX];
size_t modeSize = 0;
然后,附加大小:
if (countArray[i] > modeCount)
{
modeCount = countArray[i];
modeNumbers[0] = numArray[i];
modeSize = 1;
} else if (countArray[i] == modeCount) {
modeNumbers[modeSize++] = numArray[i];
}
最后,使用一个用于循环输出:
if (modeCount > 1) {
printf("nThe mode of the array is: ");
for (size_t i = 0; i < modeSize; ++i) { printf("%s%d", i == 0?"":", ", modeNumbers[i]; }
} else {
printf("nThe mode of the array is: None");
}