C/C++ Generating Random Numbers in C++

AI Thread Summary
To randomly select a number from an array in programming, one effective method is to use the `rand()` function to generate a random index. The example provided demonstrates initializing the random number generator with `srand(time(NULL))` to ensure different results on each run. The code snippet `random = arr[rand() % (sizeof(arr) / sizeof(arr[0]))]` shows how to pick a random element from the array by calculating the index based on the array's size. This approach effectively addresses the problem of random selection from an array.
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.
 
Thread 'Star maps using Blender'
Blender just recently dropped a new version, 4.5(with 5.0 on the horizon), and within it was a new feature for which I immediately thought of a use for. The new feature was a .csv importer for Geometry nodes. Geometry nodes are a method of modelling that uses a node tree to create 3D models which offers more flexibility than straight modeling does. The .csv importer node allows you to bring in a .csv file and use the data in it to control aspects of your model. So for example, if you...
I tried a web search "the loss of programming ", and found an article saying that all aspects of writing, developing, and testing software programs will one day all be handled through artificial intelligence. One must wonder then, who is responsible. WHO is responsible for any problems, bugs, deficiencies, or whatever malfunctions which the programs make their users endure? Things may work wrong however the "wrong" happens. AI needs to fix the problems for the users. Any way to...
Back
Top