How to store a random number in array

Hi everyone. I'm still new to programming and now I have some issue on the array So now, I had copied some example code for random+ing number in a certain range. Then I tried to write some code that store the random number in the array and then can use it in later on (doing some arithmetic with the stored number). But it always failed. Can someone please help me to solve the issue? Thanks!



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <ctime>
#include <iostream>
using namespace std;

int random(int min, int max)
{
	static bool first = true;
	if (first)
	{
		srand(time(NULL));
		first = false;

	}
	return min + rand() % (max - min);

}
int storage[5];

int main()
{
	
	cout << random(1, 5) << endl; //random 1~4

	system("PAUSE");
	return 0;


}
On line 22 you call function random() and transfer its return value directly into cout. You do want to store the value into a named variable and use the variable later.

You do ask: How to set the value of an array element?

See http://www.cplusplus.com/doc/tutorial/arrays/


An array has multiple elements and therefore you want to use a loop to repeat operation for each element.

Your line 17 declares a global variable. Move it to line 21 -- inside the function that will use the array.
Thanks for your info.
Topic archived. No new replies allowed.