樱花吃了有什么好处:请问谁有C语言的反猜数字(让电脑来猜)的源程序

来源:百度文库 编辑:高校问答 时间:2024/05/11 02:09:40
恩,我现在想要一个C语言编写反猜数字(让电脑来猜!)的源程序!谢谢了,最好有一些解释和点拨!

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{int a,b,m,k;
char ch;
again:
k=0;
_cputs("\n请输入你想好的数的范围:_至_\n");
cin>>a>>b;
m=(b+a)/2;
_cprintf("是%i吗?如果是,请输入\"y/Y\";否则,请输入\"<\"或者\">\"。\n",m);
do
{ch=_getche();k++;
if(ch=='<')a=m;
else if(ch=='>')b=m;
else
{_cprintf("\nYes!我猜对了!我猜了%i次",k);
_cputs("\n还想玩吗?(Y/N)\n");
ch=_getche();
if(ch=='Y'||ch=='y') goto again;
else {_getche(); return; }
}
m=(b+a)/2;
_cprintf("\n是%i吗?如果是,请输入\"y/Y\";否则,请输入\"<\"或者\">\"。\n",m);
}while(1);
}

好像在这里你搜一下,就可以了吧.

是猜大小还是猜几A几B的东西呢。。。大小的当然简单,几A几B的东西还是稍微有点难度的。。。全国信息学奥林匹克今年的冬令营就考了这题目。。。

A几B几需要的话邮件联系我。。。先尝后给分

//---------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#include <assert.h>
#include <string>
#include <vector>
#include <map>
#include <iostream>
#pragma hdrstop

using namespace std;

//---------------------------------------------------------------------------

string cmp_str(string s1, string s2)
{
string ret;
ret.resize(4);
ret[1] = 'A';
ret[3] = 'B';
ret[0] = '0';
ret[2] = '0';
assert(s1.length() == s2.length());
for (int i = 0; i < (int)s1.length(); i++)
{
if (s1[i] != ' ' && s1[i] == s2[i])
{
ret[0]++;
s1[i] = ' ';
s2[i] = ' ';
}
}
for (int i = 0; i < (int)s1.length(); i++)
{
if (s1[i] != ' ')
{
int pos = s2.find(s1[i]);
if (pos != -1)
{
ret[2]++;
s1[i] = ' ';
s2[pos] = ' ';
}
}
}
return ret;
}

typedef vector<string> TStrList;
typedef map<string, TStrList> TCmpStrMap;

void cmp_str_all(const string &s, const TStrList &lst, TCmpStrMap &cmpstrs, int &max_remain)
{
cmpstrs.clear();
max_remain = 0;
for (TStrList::const_iterator it = lst.begin(); it != lst.end(); it++)
{
cmpstrs[cmp_str(*it,s)].push_back(*it);
}
for (TCmpStrMap::iterator it2 = cmpstrs.begin(); it2 != cmpstrs.end(); it2++)
{
if ((int)it2->second.size() > max_remain)
max_remain = it2->second.size();
}
}

void init_lst(TStrList &lst)
{
lst.clear();
char buf[5];
for (int i = 0; i < 10000; i++)
{
snprintf(buf,sizeof(buf),"%4.4d",i);
lst.push_back(buf);
}
}

#pragma argsused
int main(int argc, char* argv[])
{
TStrList lst;
TCmpStrMap cmpstrs;
int max_remain;
string cmpstr;
int count = 0;
init_lst(lst);
srand(time(NULL));

while (lst.size() > 1)
{
count++;

string str = lst[rand()%lst.size()];
cmp_str_all(str, lst, cmpstrs, max_remain);

cout << "请输入" << str << "与您所想的数的比较结果:";
cin >> cmpstr;
for (int i = 0; i < (int)cmpstr.length(); i++)
cmpstr[i] = toupper(cmpstr[i]);
lst = cmpstrs[cmpstr];
}

cout << endl;
if (lst.size() == 1)
{
cout << "哈哈!我用" << count << "次就猜中了这个数是" << lst[0] << ",没错吧!" << endl;
}
else
{
cout << "对不起,您输入的比较结果是不可能出现的,您搞错了吧!" << endl;
}

cout << endl << "程序运行结束,按下ENTER键退出程序...";
char buf[80];
cin.getline(buf,sizeof(buf));
cin.getline(buf,sizeof(buf));
return 0;
}
//---------------------------------------------------------------------------