C笔记(4)-随机数问题

目录

一、随机数生成

1. rand

2. srand

3. time

4. 设置随机数范围

二、猜数字游戏实现


一、随机数生成

1. rand

需包含头文件:stdlib.h

rand函数生成的随机数是伪随机的,不是真正的随机数。rand函数是对叫“种子”的基准值进行运算生成的随机数

2. srand

函数原型如下:

void srand (unsigned int seed);

3. time

需包含头文件:time.h

函数原型如下

time_t time (time_t* timer);

time函数返回的是,1970年1月1日0时0分0秒到现在程序运行时间之间的差值,单位是秒。

返回类型为time_t,本质上就是32位或者64位的整型类型。

如果 timer 是NULL,就只返回这个时间的差值。time函数返回的这个时间差也被叫做:时间戳

time(NULL); //调⽤time函数返回时间戳,这⾥没有接收返回值

生成随机数的代码:

#include <stdio.h>
#include <stdlib.h> 
#include <time.h>
int main()
{
  //使⽤time函数的返回值设置种⼦
  //因为srand的参数是unsigned int类型,我们将time函数的返回值强制类型转换
  //srand函数是不需要频繁调⽤的,⼀次运⾏的程序中调⽤⼀次就够了

  srand((unsigned int)time(NULL));
  printf("%d\n", rand());
  printf("%d\n", rand());
  printf("%d\n", rand());

  return 0;
}

4. 设置随机数范围

rand() % 100; //余数的范围是0~99

rand()%100+1; //%100的余数是0~99,0~99的数字+1,范围是1~100

100 + rand()%(200-100+1);//余数的范围是0~100,加100后就是100~200

a + rand()%(b-a+1);//⽣成a~b的随机数

二、猜数字游戏实现

要求:每猜一次都给出反馈,限制猜测次数

代码实现如下:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void game()
{
	int r = rand() % 100 + 1;
	int guess = 0;
	int count = 5;
	while (count)
	{
		printf("\n你还有%d次机会\n", count);
		printf("请猜数字>:");
		scanf("%d", &guess);
		if (guess < r)
		{
			printf("猜⼩了\n");
		}
		else if (guess > r)
		{
			printf("猜⼤了\n");
		}
		else
		{
			printf("恭喜你,猜对了\n");
			break;
		}
		count--;
	}
	if (count == 0)
	{
		printf("你失败了,正确值是:%d\n", r);
	}
}
void menu()
{
	printf("***********************\n");
	printf("****** 1. play ******\n");
	printf("****** 0. exit ******\n");
	printf("***********************\n");
}
int main()
{
	int input = 0;
	srand((unsigned int)time(NULL));
	do
	{
		menu();
		printf("请选择:>");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			game();
			break;
		case 0:
			printf("游戏结束\n");
			break;
		default:
			printf("选择错误,重新选择\n");
			break;
		}
	} while (input);
	return 0;
}

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值