0

我编写了一个程序,可以生成 1000 个 1-10 范围内的随机数。然后我想要它做的是告诉我每个数字产生了多少次。但是,出于某种原因,我运行这个程序,每个数字都得到 0。

有人知道我错过了什么吗?

#include <stdio.h>
#include <stdlib.h>
void print(const int array[], int limit);

#define SIZE 1000
int main(void)
{
int i;
int arr[SIZE];

for (i = 0; i < SIZE; i++)
    arr[i] = rand() % 10 + 1;

print(arr,SIZE);

return 0;
}

void print(const int array[], int limit)
{ 
int index, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0,         
count7 = 0, count8 = 0, count9 = 0, count10 = 0;

for (index = 0; index < limit; index++)
{
    switch (array[index])
    {
        case '1' : count1++;
                  break;
        case '2' : count2++;
                  break;
        case '3' : count3++;
                  break;
        case '4' : count4++;
                  break;
        case '5' : count5++;
                  break;
        case '6' : count6++;
                  break;
        case '7' : count7++;
                  break;
        case '8' : count8++;
                  break;
        case '9' : count9++;
                  break;
        case '10' : count10++;
                 break;
        default : break;
    }

}
 printf("There were %d 10s, %d 9s, %d 8s, %d 7s, %d 6s, %d 5s, %d 4s, %d 3s, %d 2s, %d                         
 1s.", count10, count9, count8, count7, count6, count5, count4, count3, count2, count1);
}
4

2 回答 2

4

您不需要在 case 语句中的数字周围加上单引号。您正在通过包含单引号来创建字符文字。只要把它们取下来,你就会得到整数文字,这就是你想要的。

于 2013-03-19T23:07:17.720 回答
0

您正在将数字(存储在数组中)与字符文字“1”、“2”等进行比较。此外,使用数组实现打印可能会更容易:

void print(const int array[], int limit)
{ 
    int index;
    int count[11] = {0};

    for (index = 0; index < limit; index++)
    {
        count[array[index]]++;
    }
    printf("There were %d 10s", count[10]);
    for (index = 10; index > 0; index--)
    {
        printf(" %d %ds%c", count[index], index, (index > 1)?',':'.');
    }
}
于 2013-03-19T23:18:48.243 回答