Generating Random Numbers in C++

  • Context: C/C++ 
  • Thread starter Thread starter chmate
  • Start date Start date
  • Tags Tags
    C++ Numbers Random
Click For Summary
SUMMARY

The discussion focuses on generating random numbers from an array in C++. The user initially seeks assistance for selecting a random number from the array A={1,4,-1,3,-7,2,-14}. The solution provided involves using the srand() function to seed the random number generator with the current time, followed by the rand() function to select an index from the array. The final code snippet shared is: srand(time(NULL)); random = arr[rand() % (sizeof(arr) / sizeof(arr[0]))];

PREREQUISITES
  • Understanding of C++ programming language
  • Familiarity with the rand() and srand() functions
  • Knowledge of arrays in C++
  • Basic understanding of the time() function
NEXT STEPS
  • Explore the use of the std::random library in C++ for better random number generation
  • Learn about the differences between rand() and std::mt19937 for random number generation
  • Investigate how to create a custom random number generator
  • Study the implications of seeding random number generators in multi-threaded applications
USEFUL FOR

C++ developers, software engineers, and anyone interested in implementing random number generation techniques in their applications.

chmate
Messages
37
Reaction score
0
Hello!

I've been trying to create an algorithm which picks a number randomly from array. P.S i have an array like A={1,4,-1,3,-7,2,-14} and I want to pick a number randomly from array.

Any idea?

Thank you.
 
Technology news on Phys.org
Why don't you use rand() to draw index?
 
Hi borek, can you show me an example?

Thank you.
 
Hello!

I've solved my problem. I've been looking for this part of code:

srand(time(NULL));
random = arr[rand() % (sizeof(arr) / sizeof(arr[0]))];

Thank you.
 

Similar threads

  • · Replies 21 ·
Replies
21
Views
8K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
14
Views
3K
Replies
25
Views
4K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K
Replies
35
Views
7K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 12 ·
Replies
12
Views
3K
  • · Replies 31 ·
2
Replies
31
Views
3K