isdigit
函数检查参数是否为十进制数字字符。
如果您想以这种方式工作,只需将其转换为:
if (userNumber == correctNumber)
至
if (isdigit(userNumber + (char)'0'))
单词后面的语句else
仅执行if
括号中的表达式具有值0
。
如果函数return
的值isdigit
是true
(不是0
),你的代码的下一行将被执行。
在调试器下它看起来像这样:
CPU Disasm
Address Hex dump Command Comments
00401048 |. 68 24504200 push offset t3.00425024 ; /format = "%d"
0040104D |. E8 E3070000 call t3.scanf ; \scanf - Read your integer variable and store it to int
00401052 |. 83C4 08 add esp,8 ;
00401055 |. 8B45 F8 mov eax,dword ptr [ebp-8] ; Store userNumber in eax (5 in this case)
00401058 |. 83C0 30 add eax,30 ; 5 + 0x30 = 0x35 = Character 0, so decimal number is converted to char value 5
0040105B |. 50 push eax ; /c => 48., stack it
0040105C |. E8 E6020000 call t3.isdigit ; execute isdigit function - if (isdigit(userNumber+(char)'0'))
00401061 |. 83C4 04 add esp,4 ; adjust stack
00401064 |. 85C0 test eax,eax ; isdigit returned result is 0 ?
00401066 |. 74 37 jz short t3.0040109F ; if result is NOT 0, next line will be executed
00401068 |. 8B4D F8 mov ecx,dword ptr [ebp-8] ; ecx = userNumber
0040106B |. 3B4D FC cmp ecx,dword ptr [ebp-4] ; if (userNumber == correctNumber)
0040106E |. 75 0F jne short t3.0040107F ; if condition is TRUE - statement1 will be executed, otherwise statement2
00401084 |. E8 22080000 call t3.printf ; printf("Yay, you guessed it!");
....
00401081 |. E8 25080000 call t3.printf ; printf("Wrong Number!!!");
.....
0040109F |. E8 05080000 call t3.printf ; printf("That is not a number from 1 - 10");
如下所示,表达式is0
和后面的语句将else
被执行,例如。printf("That is not a number from 1 - 10");
您的初始代码如下所示:
Address Hex dump Command Comments
0040104D |. E8 E3070000 call t3.scanf ; \scanf
00401052 |. 83C4 08 add esp,8 ;
00401055 |. 8B45 F8 mov eax,dword ptr [ebp-8] ; eax is now 5, but this time the conversion is not made
00401058 |. 50 push eax ; /c => 5
00401059 |. E8 E9020000 call t3.isdigit ; \isdigit
.....
00401061 |. 85C0 test eax,eax ; isdigit returned 0 this time
00401063 |. 74 37 jz short t3.0040109C ; well, jump to last printf
.....
0040109C |. E8 05080000 call t3.printf ; \printf("That is not a number from 1 - 10");
如果使用((char) userNumber + '0')
,结果将是相同的。只有获取该值的指令才会更改为movsx eax, byte ptr [ebp-8]
。