admin管理员组文章数量:1487745
<猜数游戏>利用循环编写的游戏【C语言】
序
几天没更新了,前几天有些懒。今天我来教大家写一款猜数字的小游戏吧。 语言:C语言 编译器:vs2022 知识点:循环与分支 rand函数 srang函数 time函数
正文
废话不多说,让我们正式开始吧。 首先,我们要实现猜数字最基本的就是让电脑生成一个随机的数字,那么我们就要用到rand函数。 rand函数可以然我们的电脑产生一个随机数,但rand函数有一个缺点,他所生成的随机数是一个伪随机数,也就是说他生成的数字是固定的。
伪随机数
代码语言:javascript代码运行次数:0运行复制#include <stdio.h>
#include <stdlib.h>//rand函数的头文件
int main()
{
int a = rand();
int b = rand();
int c = rand();
int d = rand();
int r = rand();
printf("%d\n", a);
printf("%d\n", b);
printf("%d\n", c);
printf("%d\n", d);
printf("%d\n", r);
return 0;
}
即使再次运行他的数字也是这些。
真随机数
为了产生真随机数,这里我们要引入srand函数和time函数1 这两个函数可以根据时间戳产生随机数。
代码语言:javascript代码运行次数:0运行复制#include <stdio.h>
#include <stdlib.h>//rand函数的头文件
#include <time.h>//time函数的头文件
int main()
{
srand((unsigned int)time(NULL));//此处需要用到强制类型转换
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
return 0;
}
这里就生成了真随机数。
设置随机数的范围
但这里的数字都过大了,那么我们有什么办法将他们的范围控制吗? 当然是可以了 下面我将告诉你怎么操作
代码语言:javascript代码运行次数:0运行复制rand()%100//范围:0~99
rand()%100//范围:1~100
100+rand()%(200-100+1)//余数的范围是0~100,加100后就是100~200
//公式:a + rand()%(b-a+1)
实战篇
首先我们要写 基本格式
代码语言:javascript代码运行次数:0运行复制#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int input = 0;
return 0;
}
接下来运用循环
代码语言:javascript代码运行次数:0运行复制#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int input = 0;
srand((unsigned int)rand(NULL));//生成随机数
do
{
switch(input)
{
case 1:
break:
case 0:
break:
default :
break;
}
}while(input);
return 0;
}
然后我们还要运用一些别的函数
代码语言:javascript代码运行次数:0运行复制#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void game()
{
int r = rand()&100+1;
int guess = 0;
while(1)
{
printf("你打算输入 :");
scanf("%d",&guess);
if (guess > r)
{
printf("猜大了\n");
}
else if (guess < r)
{
printf("猜小了\n");
}
else
{
printf("恭喜你,猜对了\n");
break;
}
}
}
void meun()
{
printf("**************\n");
printf("*** 1.play ***\n");
printf("*** 0.exit ***\n");
printf("**************\n");
}
int main()
{
int input = 0;
srand((unsigned int)rand(NULL));//生成随机数
do
{
meun ();
printf("请输入");
scanf("%d",&input);
switch(input)
{
case 1:
game ();
break;
case 0:
printf("游戏结束");
break;
default :
printf("输入错误,请重试");
break;
}
}while(input);
return 0;
}
效果图 那么教学结束 期待你的关注
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2024-10-15,如有侵权请联系 cloudcommunity@tencent 删除游戏includeint编译器函数本文标签: <猜数游戏>利用循环编写的游戏C语言
版权声明:本文标题:<猜数游戏>利用循环编写的游戏【C语言】 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/shuma/1754822547a3180036.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论