Solved

Random Numbers in C++

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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
changePi Challenge 15 76
countPairs challenge 7 58
mapShare challenge 13 68
Tviruailstringtree sort multi columns on header click 1 31
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This article will show, step by step, how to integrate R code into a R Sweave document
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
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…

758 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

21 Experts available now in Live!

Get 1:1 Help Now