BeBreave 2015-07-15 02:46 采纳率: 40%
浏览 1451
已采纳

c 语言的问题求大神的指导!

#include"stdio.h"
#include"stdlib.h"
void main()
{
int guess=0,problem,ch;
ch=getchar();
do
{scanf("%d",&guess);
problem=(int)(rand()%100)+1;
for(;guess!=problem;)
{if(guess>problem)
printf("too high!");
if(guess<problem)
printf("too low!");
scanf("%d",&guess);
}
printf("%d",problem);
ch=getchar();
}while(ch!='n');
}为什么猜完一次数字后,我按任意键程序都会进入死循环!!

  • 写回答

3条回答 默认 最新

  • save4me 2015-07-15 03:52
    关注

    你的代码问题在于scanf没有判断输入的是否是数字,如果不是数字,就会进入死循环。加一个判断就好了。
    不过你也可以使用fgets之类的替代scanf,方便指定输入数据类型。

    #include <stdio.h>
    #include <stdlib.h>
    void main()
    {
        int guess = 0, problem;
        char ch = getchar();
        int isNumber;
        do
        {
            isNumber = scanf("%d", &guess);
            if(isNumber == 0)
            {
                printf("please input a number!");
                ch = getchar();
                continue;
            }
            problem = (int)(rand() % 100) + 1;
            for(; guess != problem;)
            {
                if(guess > problem)
                    printf("too high!");
                if(guess < problem)
                    printf("too low!");
                scanf("%d", &guess);
            }
            printf("%d", problem);
            ch = getchar();
        }while(ch != 'n');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名