我需要在C中生成随机数 [英] I need to generate random numbers in C

查看:113
本文介绍了我需要在C中生成随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复项:
如何在C语言中生成随机数?
实施rand()
在Blender3D中生成随机地形

Possible Duplicates:
How to generate a random number in C?
implementation of rand()
Generating random terrain in Blender3D

我需要C语言中的高质量随机数,但我不知道该怎么做.我需要能够从1到100取得数字.任何帮助,或者可能将我指向可以找到帮助的地方.

I need high quality random numbers in C, but I have no idea what to really do. I need to be able to get numbers from 1-100. Any help or maybe point me to where I can find help.

推荐答案

这是在C中产生均匀分布的随机数的最简单方法:

This is the simplest method of producing uniformly distributed random numbers in C:

第1步.请确保包括标准库标头以获取必要的函数原型

Step 1. Be sure to include the standard library header to get the necessary function prototypes

#include <stdlib.h>

第2步.使用srand()播种随机数生成器.种子确定随机数的起始位置.对于给定的种子,随机数的序列将始终完全相同.这使您可以获得随机但可重现的结果.如果您不希望它具有可重复性,那么最好将当前时间作为种子进行播种,这样每次运行的随机序列都会有所不同.

Step 2. Seed the random number generator using srand(). The seed determines where the random numbers start. The sequence of random numbers will always be exactly the same for a given seed. This allows you to have random, yet reproducible results. If you don't need it to be reproducible, a good thing to seed with is the current time, so that the random sequence will be different on each run.

srand(time(NULL));

(如果要执行此操作,请确保包括time.h).此外,除非您生成大量(数百万或数十亿)的随机数,否则每个程序运行仅对生成器进行一次播种.播种经常会使序列 less 变得随机.

(be sure to include time.h if you do this). Also, only seed the generator once per program run unless you are generating a huge number (millions or billions) of random numbers. Seeding frequently makes the sequence less random.

第3步.获取您的随机数.

rand()

此函数返回0到RAND_MAX之间的随机数,这是一个定义为相当大的整数的宏.

This function returns a random number between 0 and RAND_MAX, which is a macro that is defined as a rather large integer.

第4步.使您的随机数进入所需范围.这样做的一般公式是:

Step 4. Get your random number into the range you want. The general formula for doing so is this:

int random_number = rand() % range + min;

范围是您要选择的数量(连续),而min是这些中的最小值.因此,要生成1到100之间的数字,范围是100,最小值是1:

Where range is how many (consecutive) numbers you want to choose from, and min is the smallest of these. So to generate a number between 1 and 100, range is 100 and min is 1:

int random_number = rand() % 100 + 1;

有人反对这个公式,因为它使用rand()给定数字的低阶位,并且在较旧的软件伪随机数生成器实现中,它们通常比高阶位的随机性小,但是在任何现代系统中,此方法都应该很好.

Some people object to this formula because it uses the low-order bits of the number given by rand(), and in older implementations of software pseudo-random number generators these were often less random than the high order bits, but on any modern system this method should be perfectly fine.

这篇关于我需要在C中生成随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆