How do I generate random floats in C++?
I thought I could take the integer rand and divide it by something, would that be adequate enough?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
rand()can be used to generate pseudo-random numbers in C++. In combination withRAND_MAXand 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.This will generate a number from 0.0 to 1.0, inclusive.
This will generate a number from 0.0 to some arbitrary
float,X:This will generate a number from some arbitrary
LOto some arbitraryHI:Note that the
rand()function will often not be sufficient if you need truly random numbers.Before calling
rand(), you must first ‘seed’ the random number generator by callingsrand(). This should be done once during your program’s run — not once every time you callrand(). This is often done like this:In order to call
randorsrandyou must#include <cstdlib>.In order to call
time, you must#include <ctime>.