This article is a useful guide to generate random numbers in some range in C++.
Generating Random Numbers in Some Range in C++
In C++, there are two different methods for producing random numbers:
1: rand() Function
The first type of random number generation in C++ uses the library function rand(). With this function, the user provides the maximum and minimum input, and it will return a random number between those two values. The number returned can be either an integer or a floating-point number, depending on the user’s choice. The range of provided values must be positive, but it can take any value and is not limited to 0 and 1.
#include <cstdlib>
using namespace std;
int main()
{
for(int x = 0; x < 5; x++)
cout << rand() << " ";
return 0;
}
In this code, a loop is used to create random numbers five times using the built-in function rand().
Output
If you want to generate random numbers in between 0 to 1 through “rand”, you can use the following code:
#include <cstdlib>
using namespace std;
int main()
{
for(int x = 0; x < 5; x++)
cout << (rand() % 10001) / 10000.0 << " ";
return 0;
}
Output:
The issue with the rand() function is that every time we execute the program, the result will be the same sequence.
2: srand() Function
The sole difference between the srand() and rand() functions is the seed value, which is used to establish the range or sequence of the pseudo-random integers. The C++ random number generator will begin after the seed value is entered using the srand() method. The output appears random thanks to this seed value.
In this code, we are using time() function as a seed value for srand() function and then a random number is generated 5 times using a while loop.
Output
If you want to generate random numbers in between 0 to 1 through “srand”, you can use the following code:
Output
Generating Random Numbers within a Given Range – C++
It is easy to generate random numbers of a specified range in C++. To do this, a programmer must have an imaginative understanding of how random numbers can be produced and what each library, function and parameter may bring to the overall process.
In C++, the rand() function and some basic math may be used to produce a random integer within a specified range. An example of code that produces a random integer between 0 and 99 is provided here:
The current time is used to seed the random number generator in the code above, which helps to ensure that the generated random numbers are different each time the program is executed. The function rand()% 100 takes the rest of the result of rand() and multiplies it by 100 to get a random integer between 0 and 99.
Output
Conclusion
The C++ users can generate random numbers in some range using two simple methods. One is using rand() that generates random numbers in some range. However, it generates a similar number every time you execute the code. The srand() method is used to output a range of various random integers.