473,388 Members | 1,557 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

My random number is only random for the first run???


#include<iostream>
#include<cstdlib>

//This program will be a number guessing game

int main()
{
//variables for the game
int number_of_tries=0;//how many times did it take to get it right?
int current_guess=0;//the number being currently tried
int upper_limit=100;
int lower_limit=1;
int correct_number=rand()%100;//the correct number will be from no
higher than 100
while (correct_number != current_guess)
{
//user interaction
std::cout << "What is your guess? The correct number will be no higher
than 100, or lower than 1.\n";
std::cin >> current_guess;//user inputs his guess
if (current_guess > upper_limit || current_guess < lower_limit)
{
std::cout << "What, you can't read directions? The number has to be
no higher than 100, or lower than 1!!! You're Fired!!!!!\n";
std::abort();//kicks user out if input is bad
}
else if (current_guess < correct_number)
{
std::cout << "Your guess is too low. Try again\n";
number_of_tries++;
}
else if (current_guess > correct_number)
{
std::cout << "Your guess is too high. Try again\n";
number_of_tries++;
}
else if (current_guess == correct_number)
{
std::cout << "Good job! You guessed the right number!!!\n";
std::cout << "It only took you "<< number_of_tries << " tries!\n";
break;
}
}

return 0;
}
All is good for the first run. Then the wierdest thing happens... The
"random" number is always the same forever afterwards.

Jul 23 '05 #1
12 1660
xeys_00 wrote:
All is good for the first run. Then the wierdest thing happens... The
"random" number is always the same forever afterwards.

The function rand() generates pseudo-random numbers. You need to use srand()
to seed it with a different seed every time you run the program in order to
generate different sequences of random number. See the following:

http://cplus.about.com/od/cprogrammi.../aa041403b.htm

Later,
--
CrayzeeWulf
Jul 23 '05 #2
xeys_00 wrote:
int correct_number=rand()%100;//the correct number will be from no
higher than 100


You're not initializing the random seed. Do something like

srand(time(NULL));

at the very start and you'll have more "random" random numbers (although
still remaining highly deterministic).

Although in this very application not really necessary, you should
follow the advice from rand(3) how to avoid using lower-order bits in
your random numbers.

Greetings,
Johannes

--
PLEASE verify my signature. Some forging troll is claiming to be me.
My GPG key id is 0xCC727E2E (dated 2004-11-03). You can get it from
wwwkeys.pgp.net or random.sks.keyserver.penguin.de.
Also: Messages from "Comcast Online" are ALWAYS forged.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFCWGe5CseFG8xyfi4RAvMxAJsE/6CeRJdHiBXgdOGyPmmhHX5JUgCfTu1z
wH+EA75o+BSr6p9RTKQVwps=
=xX7J
-----END PGP SIGNATURE-----

Jul 23 '05 #3
Johannes Bauer wrote:
Do something like

srand(time(NULL));

Is there any difference at all between srand(time(NULL)); and srand(time(0));?

you should
follow the advice from rand(3) how to avoid using lower-order bits in
your random numbers.


Where is this advice, and how do I get it?

Thanx for your help,

wwwolf

Jul 23 '05 #4
wwwolf wrote:
Johannes Bauer wrote:
Do something like

srand(time(NULL));

Is there any difference at all between srand(time(NULL)); and srand(time(0));?


Well, yes. 0 is the number zero. NULL is the pointer zero, usually
defined as "(void*)0". The time(2) call is system specific; however on
my box, a Linux system, it demands a "time_t*" as an argument. It
requires a pointer. NULL is a pointer, 0 is not.

So when you want to go safe, use NULL, although "0" might work when your
compiler doesn't take type-safety too seriously (which _you_ should).
you should
follow the advice from rand(3) how to avoid using lower-order bits in
your random numbers.


Where is this advice, and how do I get it?


Try typing "man 3 rand" - when you've manual pages installed it comes
up. When you don't, here it is:

------------
In Numerical Recipes in C: The Art of Scientific Computing (William
H. Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling;
New York: Cambridge University Press, 1992 (2nd ed., p. 277)), the
following comments are made:

"If you want to generate a random integer between 1 and 10, you should
always do it by using high-order bits, as in

j=1+(int) (10.0*rand()/(RAND_MAX+1.0));

and never by anything resembling

j=1+(rand() % 10);

(which uses lower-order bits)."
------------

Greetings,
Johannes

--
PLEASE verify my signature. Some forging troll is claiming to be me.
My GPG key id is 0xCC727E2E (dated 2004-11-03). You can get it from
wwwkeys.pgp.net or random.sks.keyserver.penguin.de.
Also: Messages from "Comcast Online" are ALWAYS forged.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFCWJKiCseFG8xyfi4RAmMyAJ9Hg+plvUgD+h3WmnWoEF JBzq/KmwCgkA4P
ULAG03W9y3zzeO4HlIq4Hg0=
=Nskj
-----END PGP SIGNATURE-----

Jul 23 '05 #5
>> you should
follow the advice from rand(3) how to avoid using lower-order bits in your random numbers.

Where is this advice, and how do I get it?


I'm going to go out on a limb and guess that since you don't know about
the rand(3) style syntax, you're not on a *nix platform and Johannes's
instructions to type "man 3 rand" will be met with an error. In any
case, his assumption that you have man pages is quite unreasonable.

See
http://www.freebsd.org/cgi/man.cgi?q...ts&format=html

Jul 23 '05 #6
Evan wrote:
you should
follow the advice from rand(3) how to avoid using lower-order bits in your random numbers.

Where is this advice, and how do I get it?


I'm going to go out on a limb and guess that since you don't know about
the rand(3) style syntax, you're not on a *nix platform and Johannes's
instructions to type "man 3 rand" will be met with an error. In any
case, his assumption that you have man pages is quite unreasonable.

See
http://www.freebsd.org/cgi

man.cgi?query=rand&apropos=0&sektion=3&manpath=Fre eBSD+5.3-RELEASE+an
+Ports&format=html

OK, I must have had a brain fart. I wasn't thinking man at the time. rand(3)
looked too much like function() and I got a little confused.

Thanx VERY MUCH for that link. I think I will be using it often!!!
Jul 23 '05 #7
Johannes Bauer wrote:
<snip>
Try typing "man 3 rand" - when you've manual pages installed it comes
up.


Thanx, I wasn't aware that the man pages could explain functions to me. This has
opened up a whole new resource for me!
Jul 23 '05 #8
Well, thanks much. I will definitely play around with this and probably
add stuff to the prog. But I want to get the basic functionality
working first.

Xeys

Jul 23 '05 #9

"Johannes Bauer" <df***********@gmx.de> skrev i en meddelelse
news:2e************@snifftop.sniffdomain...

wwwolf wrote:
Johannes Bauer wrote:
Do something like

srand(time(NULL));

Is there any difference at all between srand(time(NULL)); and
srand(time(0));?


Johannes Baquer also wrote:
"Well, yes. 0 is the number zero. NULL is the pointer zero, usually
defined as "(void*)0". The time(2) call is system specific; however on
my box, a Linux system, it demands a "time_t*" as an argument. It
requires a pointer. NULL is a pointer, 0 is not.

So when you want to go safe, use NULL, although "0" might work when your
compiler doesn't take type-safety too seriously (which _you_ should)."

That is simply not true. First NULL simply is not defined as (void*)0 as
this would simply not work. In C++ there is no implicit conversion from
void*.
Secondly, 0 is the (only possible) representation for a null-pointer and is
both portable and type-safe. In fact you will find many (Stroustrup is one
of these) who recommend you use 0, not NULL.

/Peter

Jul 23 '05 #10
Peter Koch Larsen wrote:
"Johannes Bauer" <df***********@gmx.de> skrev i en meddelelse
news:2e************@snifftop.sniffdomain...

wwwolf wrote:
Johannes Bauer wrote:

Do something like

srand(time(NULL));

Is there any difference at all between srand(time(NULL)); and
srand(time(0));?

Johannes Baquer also wrote:
"Well, yes. 0 is the number zero. NULL is the pointer zero, usually
defined as "(void*)0". The time(2) call is system specific; however on
my box, a Linux system, it demands a "time_t*" as an argument. It
requires a pointer. NULL is a pointer, 0 is not.

So when you want to go safe, use NULL, although "0" might work when your
compiler doesn't take type-safety too seriously (which _you_ should)."

That is simply not true. First NULL simply is not defined as (void*)0 as
this would simply not work. In C++ there is no implicit conversion from
void*.


You're right, I was thinking in C, not C++.
Secondly, 0 is the (only possible) representation for a null-pointer and is
both portable and type-safe. In fact you will find many (Stroustrup is one
of these) who recommend you use 0, not NULL.


Why is that? Doesn't that defy all object-oriented concepts? I mean,
using pointers alone isn't very OO, but using integer numbers as
pointers is, well, awkward.

What reason would there be to use 0 in favor of NULL?

Greetings,
Johannes

--
PLEASE verify my signature. Some forging troll is claiming to be me.
My GPG key id is 0xCC727E2E (dated 2004-11-03). You can get it from
wwwkeys.pgp.net or random.sks.keyserver.penguin.de.
Also: Messages from "Comcast Online" are ALWAYS forged.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFCWTQCCseFG8xyfi4RAll5AKCcUwTZRpoMoG9JUvr0J6 I/Hy8OagCgnasK
vI63lPWUQeIPvBvrVErQ4sM=
=aZBO
-----END PGP SIGNATURE-----

Jul 23 '05 #11
Johannes Bauer wrote:
What reason would there be to use 0 in favor of NULL?


int main()
{
int *p = NULL;
return 0;
}

is a program that will not compile

int main()
{
int *p = 0;
return 0;
}

is a program that will compile. it is not the same as:

int main()
{
int main()
{
int x = 0;
int *p = x;
return 0;
}

because the compiler cannot guarantee x will be 0. There are two
special things about the value 0:
1) You can assign a pointer to it with no cast for any pointer type.
2) A lot of code is written to check for equality to 0 before using the
pointer. deletion of a pointer that happens to equal to 0 is also
checked and safe too.

NULL is just a
#define NULL 0
rather idiotic to use especially because its in some random header file.

Jul 23 '05 #12
As a corollary to this srand/rand question, a colleague of mine
has this code:

// Initialize the random number generator
uint32_t seed; seed += getpid() * time(NULL);
srand(seed);
int n = (seed >> 16) & 0xFFFF;
for (int i = 0; i < n; ++i) rand();

When I asked him if calling rand a random number of times would
generate a more random number, his answer was that it makes the
number "less predictable but not more random." Not sure I
understand the subtleness of the answer, but is it true?

--
Jonathan Arnold (mailto:jd******@buddydog.org)
The Incredible Brightness of Seeing, a Home Theater weblog
http://www.anaze.us/HomeTheater
Jul 23 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Virus | last post by:
Ok well what I am trying to do is have 1.) the background color to change randomly with 5 different colors.(change on page load) 2,) 10 different quotes randomly fadeing in and out in random...
16
by: Jason | last post by:
Hi, I need a way to use random numbers in c++. In my c++ project, when using the mingw compiler I used a mersenne twister that is publicly available and this did its job well. Now I have...
70
by: Ben Pfaff | last post by:
One issue that comes up fairly often around here is the poor quality of the pseudo-random number generators supplied with many C implementations. As a result, we have to recommend things like...
16
by: Leon | last post by:
I need a program that generate 5 non-duplicates random number between 1-10 as string values store in an array. Do anybody know of any good books or websites that explain how to generator random...
5
by: Peteroid | last post by:
I know how to use rand() to generate random POSITIVE-INTEGER numbers. But, I'd like to generate a random DOUBLE number in the range of 0.0 to 1.0 with resolution of a double (i.e., every possible...
12
by: Jim Michaels | last post by:
I need to generate 2 random numbers in rapid sequence from either PHP or mysql. I have not been able to do either. I get the same number back several times from PHP's mt_rand() and from mysql's...
4
by: darrel | last post by:
I can grab a random number in vb.net like this: Dim RandomClass As New Random Dim RandomNumber As Integer RandomNumber = RandomClass.Next(1, 26) However, what I want is a random number. Short...
26
by: Jimmy | last post by:
ill have a database with 1 table and 3 fields: ID FIRSTNAME LASTNAME (the ID field will be the auto incrementing index) there might be 10 records in the DB, there might be 10,000. i...
12
by: Pascal | last post by:
hello and soory for my english here is the query :"how to split a string in a random way" I try my first shot in vb 2005 express and would like to split a number in several pieces in a random way...
7
by: teh.sn1tch | last post by:
I created a random number generator for an application that uses a MersenneTwister class I found on the net. Basically I generate two random numbers from the MersenneTwister class and use each one...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.