Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,909 questions

51,841 answers

573 users

How to use the clock as a random generator seed in C++

2 Answers

0 votes
#include <iostream>
#include <random> // mt19937
#include <chrono>

int main() {
    // Use a high-resolution clock to get a more precise seed
    unsigned seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();

    // Initialize the random number generator with the seed
    std::mt19937 generator(seed);

    // Define a distribution range
    std::uniform_int_distribution<int> distribution(1, 100);

    // Generate a random number
    int random_number = distribution(generator);

    std::cout << "Random number: " << random_number << std::endl;
}



/*
run:

Random number: 15

*/

 



answered May 7, 2025 by avibootz
0 votes
#include <iostream>
#include <random>
#include <ctime>

int main() {
    // Use the current time as a seed for the random number generator
    std::mt19937 generator(static_cast<unsigned int>(std::time(nullptr)));

    // Define a distribution range
    std::uniform_int_distribution<int> distribution(1, 100);

    // Generate a random number
    int random_number = distribution(generator);

    std::cout << "Random number: " << random_number << std::endl;
}



/*
run:

Random number: 58

*/

 



answered May 7, 2025 by avibootz

Related questions

...