Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C isdigit()为整数10及以上返回true_C - Fatal编程技术网

C isdigit()为整数10及以上返回true

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

新手C学生在这里

有人能解释一下为什么isdigit()返回值为10+的true吗? 我正在做一个关于猜谜游戏的基本任务,必须使用isdigit()通知用户是否输入了数字1-10。 该程序似乎运行良好,否则,我只想知道isdigit()返回值10+为真的原因

#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
只读取一个字符。