我试图创建一个随机数猜谜游戏,生成1-10之间的随机数并让用户猜测它。然后它会告诉用户他们是否正确。该部分工作正常,但问题还要求我使用isdigit()函数。我出于某种原因无法让这个工作。它说一切都是数字。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
int main(){
srand(time(NULL));
int x;
int r;
r=(rand() %10)+1;
r=6;
printf(" Select a number between 1 and 10 \n");
scanf(" %d", &x);
if(!isdigit(x)){
if(x==r)
printf("Congratulations, you guessed correctly! \n");
else{
printf("Uh oh! You guessed the wrong number! \n");
printf("The correct guess was %d \n",r);
}
}
else{
printf("That is not a number! \n");
}
}
答案 0 :(得分:1)
数字是否需要ascii字符 - “0”,“1”,“2”,“3”......是非零返回的值。
您的代码正在获取实际值输入(作为示例104,其中ascii值为'1''''4')并将x设置为转换后的整数值,然后查看是否为ascii数值
您可能希望使用scanf的返回码来确定它是否读取了数值。
如果您要使用isdigit,则需要将该值作为字符串读取,然后对字符串中的每个字符使用isdigit来验证数字。然后使用sscanf或atoi将字符串转换为数字。