C isdigit()为整数10及以上返回true
新手C学生在这里 有人能解释一下为什么isdigit()返回值为10+的true吗? 我正在做一个关于猜谜游戏的基本任务,必须使用isdigit()通知用户是否输入了数字1-10。 该程序似乎运行良好,否则,我只想知道isdigit()返回值10+为真的原因C isdigit()为整数10及以上返回true,c,C,新手C学生在这里 有人能解释一下为什么isdigit()返回值为10+的true吗? 我正在做一个关于猜谜游戏的基本任务,必须使用isdigit()通知用户是否输入了数字1-10。 该程序似乎运行良好,否则,我只想知道isdigit()返回值10+为真的原因 #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <time.h> int main() { int i
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
int main()
{
int iRandomNum = 0;
char cResponse = '0';
srand(time(NULL));
iRandomNum = (rand() % 10) + 1;
printf("\nGuess a number between 1 and 10: ");
scanf("%c", &cResponse);
if (!isdigit(cResponse) || cResponse<'0'+1)
printf("\nYou did not enter a number 1-10");
else if ((cResponse - '0') == iRandomNum)
printf("\nCorrect!");
else
{
printf("\nSorry, you guessed wrong\n");
printf("The correct guess was %d\n", iRandomNum);
}
return 0;
}
#包括
#包括
#包括
#包括
int main()
{
int iRandomNum=0;
字符应答='0';
srand(时间(空));
iRandomNum=(rand()%10)+1;
printf(“\n请输入一个介于1和10之间的数字:”);
scanf(“%c”和对应);
如果(!isdigit(cResponse)| cResponse您正在将一个char
传递给isdigit
,该字符只能保存一个字符。因此,当您可能在10
中键入时,只有第一个字符(即数字)正在进入应答
而不是将用户输入作为字符读取,而是将其作为int读入。这样,您可以使用if(guess>=1&&guess如果添加printf
来记录应答
的值,问题将很快变得明显:
printf("\nGuess a number between 1 and 10: ");
scanf("%c", &cResponse);
printf("cResponse is %c\n", cResponse);
产出:
Guess a number between 1 and 10: 10
cResponse is 1
如您所见,只有第一个字符存储在应答中(这是有意义的,因为它只是一个字符),并且由于第一个字符是数字,因此isdigit()
调用返回true
如果要读取大于10的数字,可以改为读取int
:
int cResponse = 0;
printf("\nGuess a number between 1 and 10: ");
scanf("%d", &cResponse);
printf("cResponse is %d\n", cResponse); // prints '10' if I type '10'
请注意,在这种情况下,您不能使用isdigit()
,尽管您仍然可以使用if(response>=0&&response仅第一个字母(数字)是(输入)来轻松检查边界评估。<代码> 10 不是一个数字!和<代码> CcRe>代码> CSESESEI认为如果输入一个双字符的值,它将返回一个false。这是非常有用的,知道ISDIN在这种情况下不考虑超出第一个字符的任何东西。它不是<代码> ISDigi> <代码>。ode>Response
本身只包含一个字符,因为您要求scanf
只读取一个字符。