Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,039 questions

52,004 answers

573 users

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 99 views
1 answer 105 views
1 answer 133 views
1 answer 120 views
4 answers 305 views
305 views asked Oct 13, 2021 by avibootz
1 answer 159 views
...