Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 443
  • Last Modified:

Random Numbers in C++

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
epichero22
Asked:
epichero22
  • 3
2 Solutions
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
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
 
epichero22Author Commented:
Thanks, it worked.
0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Not a problem! ;)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now