创建一个 C 程序来计算每个数字 0-4
被键入的次数。使用 switch
-case
结构。使用 default
来计算其他字符的数量。打印特定数字的输入次数。
这是我的代码:
int main()
{
int a;
int num_0 = 0;
int num_1 = 0;
int num_2 = 0;
int num_3 = 0;
int num_4 = 0;
int num_other = 0;
printf("Input something\n");
while ((a = getchar()) != EOF)
{
switch (a)
{
case 0:
num_0++;break;
case 1:
num_1++;break;
case 2:
num_2++;break;
case 3:
num_3++;break;
case 4:
num_4++;break;
default:
num_other++;break;
};
}
printf("0 has been typed %d", num_0);printf(" times\n");
printf("1 has been typed %d", num_1);printf(" times\n");
printf("2 has been typed %d", num_2);printf(" times\n");
printf("3 has been typed %d", num_3);printf(" times\n");
printf("4 has been typed %d", num_4);printf(" times\n");
printf("other characters have been typed %d", num_other);printf(" times\n");
return 0;
}
无论我输入什么,包括0,1,2,3,4
在内的所有数字都被算作其他字符。有人可以告诉我为什么我的代码不起作用。
最佳答案
switch (a)
将比较 a
的代码。如果您输入数字,则应该是;
case '0':
num_0++;break;
case '1':
num_1++;break;
...
切换字符值而不是整数(0
的int值不是0,例如在ASCII中它是48,但我们不直接使用该值,所以它是完全便携)
也许更好的做法是创建一个表:
int count[10] = {0};
....
a -= '0'; // removes the offset
if ((a >= 0) && (a < 10)) // check bounds
{
count[a]++;
}
关于c - 使用 switch-case 结构来计算数字被输入的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48379589/