rand函数的简单使用
#include <iostream>
#include <cstdlib>
using namespace std;
/****剪刀石头布游戏****/
int main()
{
int user=0;
int pc=0;
cout<<"****这是一个剪刀石头布游戏*****"<<endl;
cout<<"0:石头 1:剪刀 2:布"<<endl;
for(;;)
{
/*这里注意***:
*
* 1.rand()函数用到了随机数种子,一旦分配后,种子的值不变。
* 所以我们要可以把它放在循环里,重复该语句就会得到不同的
* 种子的值。
* 2.如果不用循环,可以采用srand()函数来产生随机数,用法如下:
* srand(time(NULL)); //#include <time.h>
* pc=rand()%3;
*
*/
pc=rand()%3;
cout<<endl;
cout<<"请输入你要摆出的选项:";
cin>>user;
cout<<endl;
if(user>2||user<0)
{
for(;;)
{
cout<<"输入有误,请重新输入:";
cin>>user;
cout<<endl;
if(user<=2&&user>=0)
{
break;
}
}
}
cout<<"玩家摆出:"<<user<<'\t'<<"电脑摆出:"<<pc<<endl;
if(user==pc)
{
cout<<"平局!"<<endl;
}
else
{
if((user+1)%3==pc)
{
cout<<"玩家获胜!!"<<endl;
}
else
{
cout<<"电脑获胜!!"<<endl;
}
}
}
return 0;
}
//玩家(赢) 电脑(输)
//0 1
//1 2
//2 0
//(user+1)%3==pc