
davorg
Thaumaturge
/ Moderator
Aug 20, 2002, 6:08 AM
Post #8 of 8
(560 views)
|
|
Re: [abuschr] Problem with rand() function
[In reply to]
|
Can't Post
|
|
In this program, the problem is that you only set $Rand_Num to zero outside the main loop. The first time round the loop, $Rand_Num is zero. Therefore the "$Rand_Num = rand 256" code is called and $Rand_Num is set to a value. The next (and subsequent) times round the loop, $Rand_Num already has a non-zero value, so the "rand" function doesn't get called, leaving $Rand_Num containing the previous value. You should probably initialise $Rand_Num to zero at the start of each time round the loop. Personally, I'd declare $Rand_Num within the loop.
#!/usr/bin/perl # -------------------------------------------------------------------------- use strict; use warnings; my $KEY; for (1 ... 5) { my $Rand_Num = 0; # Generating a random number that is not zero. while($Rand_Num == 0) { $Rand_Num = rand 256; } # Getting the char represented by this random number. $KEY = chr($Rand_Num); print "The key is: '" . $KEY . "' and the random number is: '" . $Rand_Num . "'.\n"; } -- Dave Cross, Perl Hacker, Trainer and Writer http://www.dave.org.uk/ Get more help at Perl Monks
|