C编程帮助(计算机猜测用户正在思考的数字)

时间:2017-02-21 01:11:30

标签: c

这是我的代码:

#include <stdio.h>
#include <strlib.h>
main()
{
    int n = 50;
    int m;
    char answer[100];

    printf("Think of a number in the range of 1-%d and I'll guess it.\n",n);
    m = n/2 ;

    while( m>1 )
    {   
        printf("Is the number %d?", m);
        scanf("%s",answer);


        if (strcmp(answer,"no")==0)
            {       
                //i = n/2;
                printf("Is the number less than %d?",m);
                scanf("%s",answer);

                if(strcmp(answer,"no")==0)
                    {   
                        m = m + (n - m)/2;
                    }

                else if(strcmp(answer,"yes")==0)
                        {
                            m = m/2;
                        }                                                       
            }
        else if(strcmp(answer,"yes")==0)
            {
                printf("I have have succeeded in guessing your number. %d\n",m);
                break;
            }
    }        
}

&#34; m = m / 2;&#34;似乎存在某种问题。码。我无法弄清楚它是什么。有谁知道问题是什么?我尝试过多种方式。我似乎无法弄明白。

2 个答案:

答案 0 :(得分:0)

根据您所写的内容,我可以推断出您尝试根据是或否响应将搜索空间划分为一半。我看到的问题是你的搜索范围的下限根本没有变化,你的上界确实如此,下一个搜索键(m)实际上不是中点而是其他东西(m = m +(n - m)/ 2)导致你遇到的行为

m = 25   [ number is > 25 ] [ search-range = (0,37) ]
m = 37   [ number is > 37 ] [ search-range = (0,43) ]
m = 21   [ number is < 21 ] [ search-range = (0,10) ]
..

在上面的例子中,我们知道我们走错了方向!

逻辑需要调整每个阶段的下限和上限,从而缩小搜索范围,搜索关键字始终是该范围的中点。如果猜测的数字小于中点,则上限变为中点-1,如果它大于中点,则下限变为中点+ 1或者其匹配。 (如果下限变得大于上限,那么你要搜索的内容不在原始范围内)。基本上这是二元搜索。

以下是在您执行的示例的每次失败匹配后如何调整搜索范围的示例

25   [ number is > 25 ] [ change lower-bound search-range = (26,50) ]
38   [ number is > 38 ] [ change lower-bound search-range = (39,50) ]
44   [ number is < 44 ] [ change upper-bound search-range =  (39-43) ]
41   [ number is < 41 ] [ change upper-bound search-range =  (39-40) ]
39   <<< you have a match

答案 1 :(得分:0)

也存在逻辑错误。答案2,1(如果1至XX的范围包括1)在您的情况下无法打印正确。

50 / 2 = 25
25 / 2 = 13
13 / 2 = 6
6 / 2 = 3
3 / 2 = 1 ( condition of m > 1 will not be true and exit the loop )