Solved

Random Numbers in C++

Posted on 2013-11-19
4
387 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Enroll in May's Course of the Month

May’s Course of the Month is now available! Experts Exchange’s Premium Members and Team Accounts have access to a complimentary course each month as part of their membership—an extra way to increase training and boost professional development.

Question has a verified solution.

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

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 …
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

751 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