查找#在数组中的时间

时间:2016-08-06 00:11:36

标签: c

大家好,这个程序生成一个产生随机数组的函数。然后,它使用另一个函数来显示用户提供的数字在列表中的次数。由于输出始终为0,我在显示数字中显示的数字时遇到了麻烦。

10 32 31 5 34 39 10 15 39 25 26 10 27 21 
50 31 3 21 29 16 12 42 29 30 8 28 19 8 39 1 
19 50 34 2 4 18 40 14 34 30 40 12 41 16 32 42 
48 34 12 28 

键入一个数字以查看它在列表中显示的次数:16 。你的号码被列出0次

代码

#include <stdio.h>

int MakeRand()
{
    srand(time(NULL));
}

void fillArray( int arr[], int high)
{
    int i,N;
    N = 50;
    for (i=0;i<N;++i)
    {
        arr[i] = rand() % high +1;
        printf("%d ", arr[i]);
    }
}

int CountNumb(int arr[], int x)
{
    int k,j;
    j = 0;
    for (k=0;k<50;++k);
    {
        if (arr[k] == x)
        {
            j = j++;
        }
        return j;
    }
}

int main()
{
    int nums[50];
    int b,k,n;

    MakeRand();
    fillArray(nums,50);
    printf("Type a number to see how many times it appears in your list: ");
    scanf("%d",&n);
    b = CountNumb(nums,n);
    printf("Your number is listed %d times\n",b);
    return 0;
}

2 个答案:

答案 0 :(得分:3)

CountNumb函数中存在三个问题:

  1. for循环播放后有一个不必要的分号。
  2. 您需要j++,而不是j = j++;。您无法执行j = j++;,因为它会导致undefined behavior
  3. 您将在for循环内返回,而不是在完成for循环后返回。
  4. int CountNumb(int arr[], int x)
    {
        int k,j;
        j = 0;
        /* for (k=0;k<50;++k); */ /* Isuee 1 here, trailing semicolon */
        for (k=0;k<50;++k)
        {
            if (arr[k] == x) {
                /* j = j++; */ /* Issue 2 here, you just need j++ */
                j++;           /* Or j = j + 1;, or j += 1; but NOT j = j++ */
            }
           /*  return j; */ /* Issue 3 here, you need to return at end of function */
                            /* Not inside the for loop */
        }
        return j;
    } 
    

    您还需要include<stdlib.h>include<time.h>

答案 1 :(得分:2)

除了添加stdlib.htime.h并修复丢失的分号之外,您应该将您的return语句放在for循环之外的CountNumb()中。

按如下方式更改您的CountNumb:

int CountNumb(int arr[], int x)
  {
   int k,j;
   j = 0;
   for (k=0;k<50;++k)
    {
     if (arr[k] == x)
      {
       j++;
      }
    }
     return j;
  }

可在此处找到整个代码:codingground