how to generate number in c++
To generate a random number in C++, you can use the <random>
library. Here are the steps to do so:
- Include the
<random>
library at the beginning of your code:
#include <random>
- Create an instance of the random number generator engine. You can use the
std::random_device
class to obtain a random seed for the generator:
std::random_device rd;
std::default_random_engine generator(rd());
- Define the range of numbers you want to generate. For example, if you want to generate random numbers between 1 and 100, you can use the
std::uniform_int_distribution
class:
std::uniform_int_distribution<int> distribution(1, 100);
- Generate a random number using the generator and distribution:
int random_number = distribution(generator);
Here's the full example code:
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::default_random_engine generator(rd());
std::uniform_int_distribution<int> distribution(1, 100);
int random_number = distribution(generator);
std::cout << "Random number: " << random_number << std::endl;
return 0;
}
This code will generate a random number between 1 and 100 and print it to the console. You can adjust the range and data types as per your requirements.
Let me know if you need further assistance!