題目:請寫人與電腦猜數字的比賽(0~100)
提示:
1.人先猜或電腦猜下是隨機的(也可選擇人先猜或電腦先猜)
2.輪流猜(要顯示對方猜的數字及比答案大或小的訊息)
3.任一方猜對,遊戲就停止,並顯示誰贏了
请试一下代码
#include<iostream>
#include<time.h>
using namespace std;
int main()
{
int g,z,min=1,max=100,start;
srand(time(NULL));
z=rand()%100+1; /*计算机想一个随机数*/
start=rand()%2;
cout<<"猜数字(1-100)"<<endl;
if(start) cout<<"人先猜"<<endl;
else cout<<"机器先猜"<<endl;
while(1)
{
if (start)
{
cout<<"请输入你猜的数:";
cin>>g; /*请人猜*/
if(z==g)
{
cout<<"你赢了"<<endl;
break; /*若位置全部正确,则人猜对了,退出*/
}
else if(g>z)
{
cout<<"输入的数大了"<<endl;
if(max>g) max = g;
}
else
{
cout<<"输入的数小了"<<endl;
if(min<g) min = g;
}
start = 0;
}
else
{
g = (min+max)/2;
cout<<"电脑猜是数字是:"<<g<<endl;
if(z==g)
{
cout<<"电脑赢了"<<endl;
break; /*若位置全部正确,则人猜对了,退出*/
}
else if(g>z)
{
cout<<"输入的数大了"<<endl;
max = g;
}
else
{
cout<<"输入的数小了"<<endl;
min = g;
}
start = 1;
}
}
return 0;
}