求大神看一下这个代码
今天做c语言习题是做到这个,要求输出输入字符中各类符号的个数(函数章节)我自己打的运行时总是无法转入循环里的else部分,为什么?
#include "stdafx.h"
#include "conio.h"
int main()
{
int num = { 0 };
int blank = 0, other = 0, a, b, c;
char d = '0';
while (1)
{
d = _getch();
printf("%c", d);
a = int(d);
if (a == 27)
{
printf("\n");
break;
}
else if (48 <= a <= 57)
{
switch (a)
{
case 48:num = num + 1;
case 49:num = num + 1;
case 50:num = num + 1;
case 51:num = num + 1;
case 52:num = num + 1;
case 53:num = num + 1;
case 54:num = num + 1;
case 55:num = num + 1;
case 56:num = num + 1;
case 57:num = num + 1;
}
}
else if (d == ' '||d=='\n')
{
blank = blank + 1;
}
else
{
other = other + 1;
}
}
for (c = b = 0; b < 10; b++, c++)
{
printf("数字%d出现了%d次\n", c, num);
}
printf("空格有%d个\n", blank);
printf("其他有%d个\n", other);
return 0;
}
根据你的代码改的
#include "stdio.h"
#include "conio.h"
int main()
{
int num = { 0 };
int blank = 0, other = 0, i;
char d = '0';
while (1)
{
d = getchar();
printf("%c", d);
//a = int(d);
if (d == '\n')
{
printf("\n");
break;
}
else if (d <= '9' && d >= '0')
{
switch (d)
{
case '0':num = num + 1;break;
case '1':num = num + 1;break;
case '2':num = num + 1;break;
case '3':num = num + 1;break;
case '4':num = num + 1;break;
case '5':num = num + 1;break;
case '6':num = num + 1;break;
case '7':num = num + 1;break;
case '8':num = num + 1;break;
case '9':num = num + 1;break;
}
}
else if (d == 32 ||d == 9 || d == '\n')
{
blank = blank + 1;
}
else
{
other = other + 1;
}
}
for (i = 0; i < 10; i++)
{
printf("数字%d出现了%d次\n", i, num);
}
printf("空格有%d个\n", blank);
printf("其他有%d个\n", other);
return 0;
} else if 中的判定条件书写不对,遇到判定某个变量是否落在一个区间时请用逻辑符号连接起来,比如
48 <= a <= 57 应该写作:
a >= 48 && a <= 57 ba21 发表于 2017-7-16 22:59
根据你的代码改的
d不是char型吗,为什么可以用d==32作为判断标准?
页:
[1]