2

C语言简单实现“猜数字小游戏”

 2 years ago
source link: https://blog.51cto.com/u_15563860/5143400
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C语言简单实现“猜数字小游戏”

原创

系白杨呀 2022-03-24 13:21:08 博主文章分类:C语言学习 ©著作权

文章标签 猜数字游戏 C语言 简单实现 文章分类 其他 其它 阅读数345

C语言实现猜数字小游戏

1.编程思路:

1.首先,在主函数中设置简单的菜单函数menu()函数,然后设置一个接收用户输入的input变量,用switch循环判断用户的输入;如果用户输入1,则代表玩游戏,程序调用game()函数,如果用户输入2,则代表退出游戏,程序执行break语句,退出程序;最后为了使用户多玩几遍,在用do-while循环把上面的步骤包含。
int main()
{
int input;
srand((unsigned int)(time(NULL)));
do {
menu();
printf(“请选择:\n”);
scanf(“%d”, &input);
switch (input)
{
case 1:
game();
break;
case 2:
printf(“退出游戏!\n”);
break;
default:
printf(“输入错误,请重新输入!\n”);
break;
}
} while (input);

2.接下来开始编写menu()函数,此函数只是一个简单的打印函数,实现很简单
void menu() //菜单函数
{
printf(“\n");
printf("猜数字游戏
\n");
printf(“1.paly 2.exit\n”);
printf("
*\n”);
}
3.***第三步,也是做重要的一步,编写game()函数;
(1)产生随机数,rand()函数;而要使用rand()函数,则先要设置一个随机起点srand函数,而为了使这个起点能自动改变,这里我们引入一个概念——时间戳time(NULL)函数:当前时间-计算机起始时间(1970.1.1.0:0:0),这样,时间是一直改变的,那么我们每一次产生的数也是随机的;注:调用time()函数要加上头文件#include<time.h>
//产生随机数的两条指令
srand((unsigned int)(time(NULL)));//把time()函数的返回值强制转换成无符号int型
ren = rand()%100+1;
(2)编写循环判断用户的输入数与产生的随机数相比较:
while (1)
{
printf(“请输入你认为的数:\n”);
scanf(“%d”, &guess);
if (guess > ren) {
count++;
printf(“猜大了\n”);
}
if (guess < ren) {
count++;
printf(“猜小了\n”);
}
if (guess == ren) {
printf(“恭喜你,猜对了!\n”);
printf(“你一共猜了%d次\n”, count);
break;
}
}
3.最后在对主函数修改一下,对整个代码在优化一下,这个小游戏就完成了!

2.C语言实现的完整代码

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<windows.h>
#include<string.h>
#include<math.h>
#include<time.h> //time()
//猜数字游戏
void game() //开始玩游戏
{
int guess=0; //猜的数字
int count = 0; //统计猜的次数
int ren;
 //1.产生随机数
 //2.时间戳:当前时间-计算机起始时间(1970.1.1.0:0:0) time_t time(time_t* timer)
//srand((unsigned int)(time(NULL)));
ren = rand()%100+1; //设置1-100之间的随机数
//printf(“这个随机数是%d\n”, ren);
while (1)
{
printf(“请输入你认为的数:\n”);
scanf(“%d”, &guess);
if (guess > ren) {
count++;
printf(“猜大了\n”);
}
if (guess < ren) {
count++;
printf(“猜小了\n”);
}
if (guess == ren) {
printf(“恭喜你,猜对了!\n”);
printf(“你一共猜了%d次\n”, count);
break;
}
}
}
void menu() //菜单函数
{
printf(“\n");
printf("猜数字游戏
\n");
printf(“1.paly 2.exit\n”);
printf("
*\n”);
}
int main()
{
int input;
srand((unsigned int)(time(NULL)));
do {
menu();
printf(“请选择:\n”);
scanf(“%d”, &input);
switch (input)
{
case 1:
game();
break;
case 2:
printf(“退出游戏!\n”);
break;
default:
printf(“输入错误,请重新输入!\n”);
break;
}
} while (input);
return 0;
}

3代码运行截图

C语言简单实现“猜数字小游戏”_简单实现

  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK