Jump to content


 


Register a free account to unlock additional features at BleepingComputer.com
Welcome to BleepingComputer, a free community where people like yourself come together to discuss and learn how to use their computers. Using the site is easy and fun. As a guest, you can browse and view the various discussions in the forums, but can not create a new topic or reply to an existing one unless you are logged in. Other benefits of registering an account are subscribing to topics and forums, creating a blog, and having no ads shown anywhere on the site.


Click here to Register a free account now! or read our Welcome Guide to learn how to use this site.

Photo

Cant get random function to work in a for loop


  • Please log in to reply
1 reply to this topic

#1 mikieut

mikieut

  • Members
  • 2 posts
  • OFFLINE
  •  
  • Local time:10:25 PM

Posted 21 July 2010 - 09:43 PM

Hello,

I cant get the following code to generate multiple random numbers when I put it in a for loop in c#.
[codebox]
for (int i = 0; i < 5; i++)
{
Random random = new Random();
sentence += Convert.ToString(random.Next(1, 5));
}
return sentence;
[/codebox]

I would think this would return 5 random numbers but instead it returns the same number 5 times (between 1 & 5)

Any help would be appreciated.

Edited by mikieut, 21 July 2010 - 09:47 PM.


BC AdBot (Login to Remove)

 


#2 Billy O'Neal

Billy O'Neal

    Visual C++ STL Maintainer


  • Malware Response Team
  • 12,304 posts
  • OFFLINE
  •  
  • Gender:Male
  • Location:Redmond, Washington
  • Local time:09:25 PM

Posted 21 July 2010 - 10:18 PM

new Random()
is going to initialize a new random number generator each time through the FOR, using a random seed generated from the computer's real time clock. Your computer can do a hell of a lot more than five iterations in a second.

To fix it, move the creation of the Random out of the for loop:

Random random = new Random();
for (int i = 0; i < 5; i++)
	sentence += Convert.ToString(random.Next(1, 5));
return sentence;

Twitter - My statements do not establish the official position of Microsoft Corporation, and are my own personal opinion. (But you already knew that, right?)
Posted Image




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users