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

Discussion Overview

The discussion revolves around generating random numbers in C++, specifically focusing on selecting a random element from an array. The scope includes algorithmic approaches and practical coding solutions.

Discussion Character

  • Technical explanation

Main Points Raised

  • One participant inquires about an algorithm to randomly select a number from an array containing integers.
  • Another participant suggests using the `rand()` function to generate a random index for selection.
  • A different participant requests an example of how to implement the suggested approach.
  • A later reply shares a solution involving `srand(time(NULL))` and the use of `rand()` to select a random element from the array.

Areas of Agreement / Disagreement

The discussion does not appear to have any significant disagreement, as participants build on each other's suggestions and a solution is provided.

Contextual Notes

There may be assumptions regarding the initialization of the random number generator and the handling of the array size that are not explicitly detailed in the discussion.

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 2 ·
Replies
2
Views
2K
Replies
35
Views
8K
  • · Replies 12 ·
Replies
12
Views
3K
  • · Replies 31 ·
2
Replies
31
Views
3K