I just started learning c++ and I was trying to recreate an old blackjack program I had made in high school to test what I have learned in my course.
Anyway, every time i use rand() i get the same numbers every single time I run the program. IE, the first "hand" that is played is always [ 7, 11 ]. How can I make it so that the generated numbers are random every time?
This code is not complete for a blackjack program, but I need to overcome this rand() issue before I move on to other calculations. It currently compiles and works as is without any other issues.
// This program demonstrates random numbers.
#include <iostream>
#include <cstdlib> // rand and srand
#include <ctime> // For the time function
usingnamespace std;
int main()
{
// Get the system time.
unsigned seed = time(0);
// Seed the random number generator.
srand(seed);
// Display three random numbers.
cout << rand() << endl;
cout << rand() << endl;
cout << rand() << endl;
return 0;
}
#include <iostream>
#include <chrono> //For system_clock
#include <random>
int main()
{
// construct a trivial random generator engine from a time-based seed:
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator(seed);
std::uniform_real_distribution<double> distributionDouble(1.0, 10.0); // Set the numbers for double.
std::uniform_int_distribution<int> distributionInteger(1, 10); // Set the numbers for int.
std::cout << "some random numbers between 1.0 and 10.0:\n";
for (int i = 0; i < 10; ++i)
{
std::cout << distributionDouble(generator) << " ";
}
std::cout << std::endl;
std::cout << "some random numbers between 1 and 10: ";
for (int i = 0; i < 10; ++i)
{
std::cout << distributionInteger(generator) << " ";
}
std::cout << std::endl;
return 0;
}