为什么我不能在C语言的Switch语句中使用数组?

时间:2013-03-19 23:05:16

标签: c switch-statement

我编写了一个程序,可以生成1,000个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);
}

2 个答案:

答案 0 :(得分:4)

case语句中的数字周围不需要单引号。您通过包含单引号来创建字符文字。只要把它们拿走就可以得到整数文字,这就是你想要的。

答案 1 :(得分: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)?',':'.');
    }
}