How to generate a random number in C++

4 Answers

0 votes
#include <iostream>
#include <ctime>

using namespace std;

int main()
{
	srand((unsigned)time(0));

	for (int i = 0; i < 10; i++)
	{
		int n = rand();
		cout << n << endl;
	}

	return 0;
}


/*
run:

19575
6595
21638
9588
13175
14776
15881
13322
12444
10450

*/

 



answered Feb 16, 2017 by avibootz
0 votes
#include <iostream>

using namespace std;

int main()
{
	for (int i = 0; i < 10; i++)
	{
		int n = rand();
		cout << n << endl;
	}

	return 0;
}


/*
run:

41
18467
6334
26500
19169
15724
11478
29358
26962
24464

*/

 



answered Feb 16, 2017 by avibootz
0 votes
#include <iostream>
#include <ctime> 

using namespace std;

int main()
{
	srand((unsigned)time(0));
	
	int n;

	for (int i = 0; i < 20; i++)
	{
		n = (rand() % 4) + 1; // 1 - 4
		cout << n << endl;
	}

	return 0;
}


/*
run:

3
2
3
3
4
1
1
2
3
3
4
2
4
1
1
1
4
4
1
4

*/

 



answered Feb 16, 2017 by avibootz
0 votes
#include <iostream>
#include <ctime> 

using namespace std;

int main()
{
	srand((unsigned)time(0));

	int n;
	int min = 3, max = 7;

	int range = (max - min) + 1;

	for (int i = 0; i < 20; i++) 
	{
		n = min + int(range * rand() / (RAND_MAX + 1.0));
		cout << n << endl;
	}

	return 0;
}


/*
run:

6
4
4
3
5
3
4
7
5
3
3
5
5
5
3
6
5
3
7
5

*/

 



answered Feb 16, 2017 by avibootz

Related questions

2 answers 124 views
1 answer 130 views
1 answer 190 views
1 answer 177 views
4 answers 353 views
353 views asked Oct 13, 2021 by avibootz
1 answer 175 views
...