完工,不会再改了,最后那个猴子撒网真的在搞笑,你可以尝试改一下代码里的rand_max的值,数据量大了就爆了。。。
#include<iostream>
#include<cstdlib>
#include<time.h>
using namespace std;
//--------------函数声明---------------------------
int give_num(); //给数函数(只调用一次,防bug)
int game(); //游戏函数
void _auto(); //自动化
//-------------------------------------------------
const int guess = give_num(); //定义常量防止变化!之前怎么就没想到呢!??
const int rand_max = 100;
int main()
{
int ch;
char ch2;
loop:
cout << "1.开始" << endl;
cout << "2.自动猜数 (无实际用途,算法练习) " << endl;
cout << "3.结束游戏" << endl;
cin >> ch;
system("cls");
switch (ch)
{
case 1:
while (1)
{
game();
if (game() == 1)
{
//cout << "您共猜了" << sum() << "次" << endl;
cout << "您赢了,请问您要再来一次吗?" << endl;
cout << "y/n" << endl;
cin >> ch2;
if (ch2 == 'y')
{
goto loop;
}
else if (ch2 == 'n')
{
break;
}
}
else if (game() == 2)
{
cout << "太小了" << endl;
}
else if (game() == 3)
{
cout << "太大了" << endl;
}
}
case 2:
_auto();
case 3:
break;
default:
cout << "请不要乱输!" << endl;
goto loop;
break;
}
system("pause");
}
int give_num()
{
int givenum;
srand((unsigned)time(NULL));
givenum = (rand() % rand_max) + 1;
return givenum;
}
int game()
{
int yourguess;
cout << ">>> ";
int gnum = guess;
while (1)
{
cin >> yourguess;
while (yourguess != gnum)
{
if (yourguess < gnum)
{
return 2;
}
else if (yourguess > gnum)
{
return 3;
}
}
while (yourguess == gnum)
{
return 1;
}
}
}
void _auto() //就是玩的,猴子撒网算法,时间复杂度为O(n*n!)
{
int yourguess = give_num(), cnum, k = 0;
while (1)
{
int cnum = (rand() % rand_max) + 1;
k++;
cout << "您猜了: " << cnum << endl;
if (cnum == yourguess)
{
cout << "您终于赢了" << endl;
cout << "您共猜了" << k << "次" << endl;
break;
}
}
}