我的代码出了什么问题?即使我输入一个数字在1-10之间或其他任何东西,它直接进入"你没有输入正确的号码"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
// CREATE A VARIABLE TO STORE A RANDO NUMBER ITS TIME THE PROGRAM RUNS
int numdef, randomnum ;
//ASSIGN RANDOM NUMBER
numdef = (rand() % 11);
//PROMT USER TO GUESS A NUMBER BETWEEN 1-10
printf("Please enter a number between 1-10\n");
scanf("%d", &randomnum);
// USE SDIGIT TO VERIFY THAT USER ENTERS A DIGIT
if (isdigit(randomnum))
printf("correct");
// LET HIM KNOW IF HE IS CORRECT OR NOT
else
printf("\nYou did not enter a correct number FOOL!!!,please try again! \n");
return 0;
}
答案 0 :(得分:4)
因为isdigit()
检查传递的值是否是数字的ascii代码。您正在向其传递一个数字,因此它始终提供0
。
isdigit()
检查x
的值是否满足'0' < x < '9'
,其中'0'
和'9'
是字符0
的ascii值和9
分别为48
和57
。
您正在使用scanf()
阅读一个数字,您无需检查是否为数字。必须提供scanf()
成功,以验证您必须检查scanf()
的返回值,它是成功扫描的占位符的数量。
所以在你的情况下
if (scanf("%d", &randomnum) != 1) // The 1 is for the lonely "%d"
printf("Error, the text entered is not a number\n");
else
printf("You entered `%d'\n", randomnum);
// Trying to read from `randomnum' here is dangerous unless it was
// initialized before `scanf()'.