Printing out random values

I canĀ“t get the the loop to get a new random value at every new number cin

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
29
30
31
32
33
34
  #include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

int number;
int randomNumber;

int main()
{

	cout << "Write how many times the crown will be thrown: " << endl;
	cin >> number;


	for (int i = 0; i < number; i++)
	{
		srand(time(0));
		randomNumber = (rand ()% 2) + 1;

		if (randomNumber == 1)
		{
			cout << randomNumber << "Crown" << endl;
		}
		else if (randomNumber == 2)
		{
			cout << randomNumber << "Tails" << endl;
		}
	}
	
	return 0;
}
Last edited on
That's because you're reinitializing the random number generator every time through the loop at line 20. srand should only be called ONCE at the beginning of your program. Therefore, the random number generator returns the same sequence of numbers.

Move line 20 before line 18.

Last edited on
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
29
30
31
32
33
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

int number;
int randomNumber;

int main()
{

	cout << "Write how many times the coin will be thrown: " << endl;
	cin >> number;
	srand(time(0));		
		
	for (int i = 0; i < number; i++)
	{
		randomNumber = (rand ()% 2) + 1;
		
		if (randomNumber == 1)
		{
			cout << "Crown" << endl;
		}
		else if (randomNumber == 2)
		{
			cout << "Tails" << endl;
		}
	}
	
	return 0;
}
Topic archived. No new replies allowed.