C ++随机浮点数生成 [英] C++ random float number generation

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

问题描述

如何在C ++中生成随机浮点?

How do I generate random floats in C++?

我想我可以接受整数rand并除以某个值,是否足够? >

I thought I could take the integer rand and divide it by something, would that be adequate enough?

推荐答案

rand()可用于在C ++中生成psudo-随机数。结合 RAND_MAX 和一个小数学,您可以在任意任意间隔生成随机数。这足以用于学习目的和玩具程序。如果您需要真正具有正态分布的随机数字,您需要使用更高级的方法。

rand() can be used to generate psudo-random numbers in C++. In combination with RAND_MAX and a little math, you can generate random numbers in any arbitrary interval you choose. This is sufficient for learning purposes and toy programs. If you need truly random numbers with normal distribution, you'll need to employ a more advanced method.

这将生成一个从0.0到1.0的数字,包括0.0和1.0。

This will generate a number from 0.0 to 1.0, inclusive.

float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);

这将生成一个从0.0到某个任意 float X

This will generate a number from 0.0 to some arbitrary float, X:

float r2 = static_cast <float> (rand()) / (static_cast <float> (RAND_MAX/X));

这将从一些任意的 LO 到某些任意的 HI

This will generate a number from some arbitrary LO to some arbitrary HI:

float r3 = LO + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(HI-LO)));






注意 rand


Note that the rand() function will often not be sufficient if you need truly random numbers.

如果您需要真正的随机数,则 rand(),必须首先通过调用 srand()种子随机数生成器。这应该在程序运行期间执行一次 - 而不是每次调用 rand()时执行一次。这通常这样做:

Before calling rand(), you must first "seed" the random number generator by calling srand(). This should be done once during your program's run -- not once every time you call rand(). This is often done like this:

srand (static_cast <unsigned> (time(0)));

要调用 rand srand 您必须 #include< cstdlib>

要订购时间,您必须 #include< ctime>

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

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