我正在尝试创建一个生成随机数的程序,要求用户猜测,然后回答他是否正确.出于某种原因,无论用户是否输入数字,它都会响应,就好像他没有.有任何想法吗?谢谢你帮助初学者:)
#include<stdio.h>
#include<ctype.h>
#include<time.h>
main()
{
char iRandomNum = '\0';
int iResponse = 0;
srand(time(NULL));
iRandomNum = (rand() % 10) + 1;
printf("Guess the number between 1 yand 10 : ");
scanf("%d", &iResponse);
if (isdigit(iResponse) == 0)
printf("you did not choose a number\n");
else if (iResponse == iRandomNum)
printf("you guessed correctly\n");
else
printf("you were wrong the number was %c", iRandomNum);
}
Run Code Online (Sandbox Code Playgroud)
isdigit()获取一个字符的ascii值,0如果它不是数字则返回,如果不是则返回非数字0.
你传递给它一个整数值,它不一定是ascii值,你不需要检查它是否是一个数字,因为你读它scanf().
如果您想确保scanf()读取了一个数字,请检查返回值scanf().
试试这个
if (scanf("%d", &iResponse) != 1)
printf("you did not choose a number\n");
Run Code Online (Sandbox Code Playgroud)
而不是 if (isdigit( ...
还有一件事,main()必须回归int.
| 归档时间: |
|
| 查看次数: |
1083 次 |
| 最近记录: |