随机函数问题!
题目:
这是一个有趣的猜拳游戏,参与游戏的双方是您和电脑。
用C语言编写一个程序来实现这个游戏。程序中让您选择1、2、3出拳(其中1代表石头,2代表剪子,3代表布),程序则使用1个1—3之间的随机数出拳(电脑出拳),判断胜负并显示结果。这个猜拳游戏会一直继续下去,直到您不想玩了。
三、实现的步骤
1、 定义程序中使用的变量。
2、 接受用户出拳,使用函数完成用户出拳的功能。
3、 完成电脑出拳,使用函数完成电脑出拳的功能。
4、 判断胜负,使用函数完成判断胜负功能。
5、 进行循环判断。
6、 具体运行结果请参考图1
部分代码:
#include<stdio.h>
#include<time.h>
#include<stdlib.h>]
int a; // 用来存放用户的选择
int b; // 用来存放电脑的选择
void customer(); // 用来获取用户的合法输入,其值保存在a中
void computer();// 用来获取计算机的输入,其值保存在b中
void computer()
{
srand((unsigned)time(NULL));
b=rand()%3+1;
if(b==1)
printf("My choice is:stone\n");
else if(b==2)
printf("My choice is:scissors\n");
else if(b==3)
printf("My choice is:cloth\n");
return y;
}
void compare(int u , int v)
{
if(b==a)
printf("Our choice are the same.\n");
else if(b==1)
{
if(a==2) printf("I'm sorry I lose the game.\n");
else if(a=3) printf("Ha Ha ! I win the game.\n");
}
else if(b==2)
{
if(a==1) printf("I'm sorry I lose the game.\n");
else if(a==3) printf("Ha Ha ! I win the game.\n");
}
else if(b==3)
{
if(a==1) printf("Ha Ha ! I win the game.\n");
else if(a==2) printf("I'm sorry I lose the game.\n");
}
}
void main()
{
char x;
do
{
customer();
computer(b);
compare(a,b);
printf("Do you want to continue?(Y/N)");
scanf(" %c",&x);
}while(x=='y' || x=='Y');
}
// 该函数用来获取用户的选择,并保存在a中
void customer()
{
// 获取用户的有效输入
do
{
printf("Please enter your choice?(1--stone 2--scissors 3--cloth):");
scanf("%d",&a);
if(a<1||a>3)
{
printf("Your choice is invalid!\n");
}
}while(a<1||a>3);
// 显示用户的选择
if(a==1)
{
printf("Your choice is:stone\n");
}
else if(a==2)
{
printf("Your choice is:scissors\n");
}
else if(a==3)
{
printf("Your choice is:cloth\n");
}
}
问题:
b=rand()%3+1; //是生成随机函数
我想问问大家为什么要%3+1这是什么意思呢?这样会产生什么结果呢?