Solved

Random Numbers in C++

Posted on 2013-11-19
4
383 Views
Last Modified: 2013-11-19
Hi,


I'm trying to generate some random numbers in C++, so this is my code:

	for (int i = 0; i < 5; i++)
	{

		cout << rand() << endl;

	}

Open in new window


However, every time I run this, it gives me the same sequence of numbers.  Is there a better way to generate random numbers?

Thanks!
0
Comment
Question by:epichero22
  • 3
4 Comments
 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
ID: 39661299
You are generating them properly. The problem is that you have to "seed" the random number generator with a different value each time you run your program, so that you get different sequences. Add this line before your for loop...
srand(time(NULL));

Open in new window

0
 
LVL 35

Assisted Solution

by:mccarl
mccarl earned 500 total points
ID: 39661304
Note: you may need to add an include at the top of your file for time() to work...
#include <time.h>

Open in new window

0
 
LVL 11

Author Closing Comment

by:epichero22
ID: 39661434
Thanks, it worked.
0
 
LVL 35

Expert Comment

by:mccarl
ID: 39661460
Not a problem! ;)
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
draw a Christmas tree by using a nested loop? 26 78
Object Oriented Programming, C#, referencing, scoping. 13 69
asp Google Map 2 33
IDE for Python 5 27
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question