Solved

Random Numbers in C++

Posted on 2013-11-19
4
376 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

I know it’s not a new topic to discuss and it has lots of online contents already available over the net. But Then I thought it would be useful to this site’s visitors and can have online repository on vim most commonly used commands. This post h…
This article will show, step by step, how to integrate R code into a R Sweave document
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

929 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now