Question:
In C++, how do I generate random numbers?
Peter
2011-08-03 02:04:27 UTC
Hey, I want to generate random numbers from 1 to 8, how do I do this in c++? I have only just started learning this so dont have much of an idea. I know in javascript you would go Math.ceil(Math.random()*8) to generate the random numbers between 1 and 8. So how do I do this? An example would be great, thanks.
Five answers:
Priyanka
2011-08-03 03:34:05 UTC
include

#include



main()

{

int n, max, num, c;



cout << "Enter the number of random numbers you want ";

cin >> n;

cout << "Enter the maximum value of random number ";

cin >> max;



cout << "random numbers from 0 to " << max << " are :-" << endl;



for ( c = 1 ; c <= n ; c++ )

{

num = random(max);

cout << num << endl;

}



return 0;

}
?
2011-08-03 10:18:44 UTC
You have a few options

1. You can use the C standard library function rand(). It returns a value between 0 and RAND_MAX (some platform-specific big integer number), inclusive, as long as you remembered to seed it with srand() earlier.

To shrink the 0..RAND_MAX inclusive range to 1..8 inclusive, you again have options



1a if you do not mind degrading the uniformity of your distribution in favor of simple code, you can use modulus to shrink that range.



     srand(seed);

     ...

    int value = 1 + rand() % 8



test: https://ideone.com/SY6AZ



2a If you need slightly more uniform distribution 1..8, use floating-point division to shrink that range



     srand(seed);

     ...

     int value = 1 + rand() / (RAND_MAX+1.0) * 8;



test: https://ideone.com/vqggI



2. If your compiler is reasonably new (after 2005 or whenever it implemented TR1. Visual Studio 2010 and gcc 4.4 definitely work) or if your compiler is old but don't mind using the boost library, you can use the C++ standard library facilities instead. There you have a wide variety of random number generators and random number distributions to choose from.



     mt19937 eng(seed); // Mersenne twister RNG

     uniform_int_distribution<> dis(1, 8);

     ...

     int value = dis(eng);



test: https://ideone.com/GLW8g
Lonely Wolf
2011-08-03 09:08:37 UTC
#include

{

number=rand()%7 + 1

}
Blackcompe
2011-08-03 09:54:54 UTC
This question has been asked already. Use the search engine first. See https://answersrip.com/question/index?qid=20110802180851AA9COCM
dan
2011-08-03 09:06:11 UTC
This should show you all you need: http://adf.ly/2Gt3G


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...