(猜数字游戏)————————————————————————猜数字游戏要求电脑会生成一个随机数猜大小(给出大小提示)次数不限————————————————————————函数说明1. rand() 函数ra...

(猜数字游戏)
————————————————————————
猜数字游戏要求
- 电脑会生成一个随机数
- 猜大小(给出大小提示)
- 次数不限
————————————————————————
函数说明
1. rand() 函数
rand()函数: 生成一个随机数。
会随机返回一个随机整数 (0~32767)
在头文件 stdlib.h 中
(Use the srand function to seed the pseudorandom-number generator before calling rand)
在调用rand之前,要使用 srand 函数去设置那个随机数的生成器。如果不使用 srand 则每重新运行生成的随机数一样。
若想要输出的数在0~100之间,只要 rand()%100+1
2. 时间戳:
当前计算机的时间 ==-(减)== 计算机的起始时间(1970.1.1 0:0:0) ==\=== (....)秒
3. time() 函数
time()函数: 获取系统时间
*time_t time(time_ttimer); time_t类型—>本质上就是长整型
在头文件 time.h** 中
4. srand() 函数
srand()函数:设置一个随机起点
void srand(unsigned int seed); ← ()里面是整形
一般拿时间戳来设置随机数的生成起始点。
在整个代码中设置一次就行,一般在主函数设置一次就行。不要频繁的调用。
————————————————————————
代码
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void menu()
{
printf("————————————————\n");
printf("** 1.开始游戏 0.结束 **\n");
printf("————————————————\n");
}
void game()
{
//1.生成一个随机数 ret :
int ret=0,i;
ret=rand()%100+1;//专门用来生成随机数的函数、rand()%100+1 表示随机数在0~100之间
printf("****\n");
//2.猜数字:
while(1)
{
printf("猜数字: ");
scanf("%d",&i);
if(i>ret)
printf("大了\n");
else if(i<ret)
printf("小了\n");
else
{
printf("!!猜对了!!\n");
break;
}
}
}
int main()
{
srand((unsigned int)time(NULL)); //void srand(unsigned int seed) 所以要强制类型转换,time(指针)所以用NULL空指针
int input;
do //游戏至少要进去一次
{
menu();
printf("请选择:");
scanf("%d",&input);
switch(input)
{
case 1:
game();break;
case 0:
printf("结束游戏\n");break;
default:
printf("输入错误\n");break;
}
}while(input); //input为1或者其他值的时候是 真 ,继续循环。为0的时候跳出循环。这样可以多次玩
return 0;
}
运行结果
↓ ↓
本文标题为:【C语言】猜数字游戏


基础教程推荐
- C++中的atoi 函数简介 2023-01-05
- C语言基础全局变量与局部变量教程详解 2022-12-31
- C++使用easyX库实现三星环绕效果流程详解 2023-06-26
- C利用语言实现数据结构之队列 2022-11-22
- 详解c# Emit技术 2023-03-25
- C/C++编程中const的使用详解 2023-03-26
- C语言 structural body结构体详解用法 2022-12-06
- 一文带你了解C++中的字符替换方法 2023-07-20
- 如何C++使用模板特化功能 2023-03-05
- C++详细实现完整图书管理功能 2023-04-04