首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

求猜数目字算法循环次数最少的算法

2012-10-13 
求猜数字算法循环次数最少的算法大虾们,小脑脑袋不好使,借各位大虾的一用,请给出实现代码,要求如下。要求如

求猜数字算法循环次数最少的算法
大虾们,小脑脑袋不好使,借各位大虾的一用,请给出实现代码,要求如下。

要求如下:

我的要求不一样哦

猜字某个数字键在1~256的范围。

比方数字88

1、你猜80,我只能告诉你 < 某数(我不能告诉你是否等于)
2、你猜87,我只能告诉你 < 某数(我不能告诉你是否等于)
3、你猜88,我只能告诉你 > 某数(我不能告诉你是否等于)
4、你猜89,我只能告诉你 > 某数(我不能告诉你是否等于)

根据第2条,和第3条,就基本可以确定,正确答案是88

算法怎么写,请你们帮帮,我要求,验证次数最少 (你报数的时候,我不能告诉你是否等于,只能根据连续二个数确定)





[解决办法]

C/C++ code
int Guess(int begin,int end, int x){    static int count =0;        //猜的次数    ++count;            int num = (begin+end)/2;    if(num>x)    {        printf("%d 大于未知数 x\n",num);        Guess(begin,num,x);    }    else if(num<x)    {        printf("%d 小于未知数 x\n",num);        Guess(num,end,x);    }    else        //猜对的时候        printf("%d 大于未知数 x\n",num);            return count;}
[解决办法]
C/C++ code
#include <stdio.h>  #include <stdlib.h>  #include <time.h>int key;char feedback(int num){    if (num >= key)    {        printf("%3d: %3d > key\n", num, num);        return '>';    }    else    {        printf("%3d: %3d < key\n", num, num);        return '<';    }    }int guess(){    int start = 1, end = 256;    int m ;    int total = 0;    while (1)    {        m = (start + end)/2;        total++;        if (feedback(m) == '>')        {            total++;            if (feedback(m - 1) == '>')            {                end = m - 1;            }            else            {                printf("\nKey is %d\n(Tryed %d times)\n", m, total);                return m;            }        }        else        {            total++;            if (feedback(m + 1) == '<')            {                start = m + 1;            }            else            {                printf("\nKey is %d\n(Tryed %d times)\n", m + 1, total);                return (m + 1);            }        }    }}int main(){    srand((unsigned)time(NULL));    key = rand()%256 + 1;    printf("Guess Key:\n\n");    guess();    return 0;}
[解决办法]
这个应该可以了,和你的http一样了。
C/C++ code
#include <iostream>#include <time.h>#include <cstdlib>using namespace std;int keytarget = 74;bool http( int num ){    if( num > keytarget )        return false;    else        return true;}void Guess( ){    int low = 1;    int high =256;    while( low<=high )    {        cout <<"Please Guess a Number:\n"<<endl;        int mid = (low+high)/2;        cout <<"Is "<< mid <<" ?\n"<<endl;        if( !http(mid) ){            cout << "大于目标\n"<<endl;            high = mid - 1;        }        else{            cout << "小于目标\n"<<endl;            low = mid + 1;        }    }}int main(){    /*srand((unsigned int)time(0));    int Target = rand()%256+1;*/        Guess();    //cout << "The target is " << Target << endl;    return 0;} 

热点排行