Z
zwhc
Unregistered / Unconfirmed
GUEST, unregistred user!
如下的猜数程序有个 bug: 如果输入的数据为字符,将陷入死循环
如何让程序可运行?
===============================================================
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int magic;
/* magic number */
int guess;
/* user's guess */
magic = rand();
/* get a random number */
printf("Guess the magic number: ");
for(guess=0;
guess!=magic {
if (scanf("%d", &guess) ==0 ) continue;
printf("%d", guess);
/* guess = gets(stdin);
*/
if (guess == magic) {
printf("** Right **");
printf(" %d is the magic number/n", magic);
}
else
{
printf("Wrong, ");
if(guess > magic) printf("too high/n");
/* nested if */
else
printf("too low/n");
}
}
return 0;
}
如何让程序可运行?
===============================================================
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int magic;
/* magic number */
int guess;
/* user's guess */
magic = rand();
/* get a random number */
printf("Guess the magic number: ");
for(guess=0;
guess!=magic {
if (scanf("%d", &guess) ==0 ) continue;
printf("%d", guess);
/* guess = gets(stdin);
*/
if (guess == magic) {
printf("** Right **");
printf(" %d is the magic number/n", magic);
}
else
{
printf("Wrong, ");
if(guess > magic) printf("too high/n");
/* nested if */
else
printf("too low/n");
}
}
return 0;
}