在C中编码多种模式吗?

时间:2018-10-18 03:17:42

标签: c arrays mode

我的任务是为一组数字(0到100)找到所有可能的模式。

我们被告知要使用数组,还要计算每个数字出现的频率。

我已经为模式编码,但是,我的程序无法运行,因为存在多种模式(例如:1, 2, 7, 7, 9, 10, 7, 2, 2。在这种情况下,27都是模式,我的程序需要同时打印它们,但我的不需要。

我认为我可能必须设置另一个数组,但是我不确定吗?任何意见,将不胜感激。

这里是我所拥有的:

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

int main() {
    int x, i, c[101], mode;

    printf("please enter test scores between 0 and 100\n");

    i = 0;
    mode = 0;

    while (i <= 100) { //setting all values to 0 
        c[i] = 0;
        i = i + 1;
    }

    scanf("%d", &x); // scanning in the test scores 

    while ((x >= 0) && (x <= 100)) { // counting how often each score appears 
        c[x] = c[x] + 1;

        if (c[x] >= mode) {
            mode = x;
        }

        scanf("%d", &x);
    }

    printf("THE MODE(S) ARE %d\n", mode);

    i = 0;

    while (i <= 100) { //printing all values so long as they've occurred at least once 
        if (c[i] > 0) {
            printf("%d occurs %d times\n", i, c[i]);
        }
        i = i + 1;
    }
}

2 个答案:

答案 0 :(得分:1)

您必须计算任何数字的最高频率,如果该频率等于任何其他数字的频率,则该数字也将成为模式。 因此,您需要做的更改是:

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

int main ()
{
  int x, i, c[101], mode;
  printf("please enter test scores between 0 and 100\n");
  i = 0;
  mode = 0;
  while (i <= 100) //setting all values to 0 
    {
      c[i] = 0;
      ++i;
    }
  scanf("%d", &x); // scanning in the test scores 
  while ((x >= 0) && (x <= 100)) // counting how often each score appears 
    {
      c[x] = c[x] + 1;
      if (c[x] >= mode)
      {mode = c[x];}
      scanf("%d", &x);
    }
  for(i=0;i<=100;i++){//printing all values having highest frequency
    if (c[i]==mode)
    {
        printf("THE MODE(S) ARE %d\n", i);
   }
   i = 0;
   while (i<=100) //printing all values so long as they've occurred at least once 
   {
   if (c[i] > 0)
     {
       printf("%d occurs %d times\n", i, c[i]);
      }
   ++i;
   }
}

答案 1 :(得分:1)

应该确定最大计数,而不是确定主进入循环中的模式。然后,您可以在最终循环中打印出具有此出现次数的所有值。

您还应该检查scanf()的返回值。

我还建议对数组使用一个初始化程序,以避免循环,并使用for循环来更清楚地标识循环索引的初始化,测试和增量。

这是您的代码的更正版本:

#include <stdio.h>

int main() {
    int x, i, c[101] = { 0 }, max_repeat;

    printf("please enter test scores between 0 and 100\n");

    max_repeat = 0;

    // read the test scores and compute the maximum repeat count
    while (scanf("%d", &x) == 1 && x >= 0 && x <= 100) {
        c[x] += 1;
        if (max_repeat < c[x]) {
            max_repeat = c[x];
        }
    }

    printf("The mode(s) are");

    for (i = 0; i <= 100; i++) {
        if (c[i] == max_repeat) {
            printf(" %d", i);
        }
    }
    printf("\n");
    return 0;
}