473,396 Members | 2,018 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,396 software developers and data experts.

Where is my mistake?

I am self study C program student.
Hope someone can help me with this problem.
This program generates random numbers over a user defined range using call function
I used the call function " GenRndNum". The range is 2 and 10.
The problem is that I get the same 2 random numbers generated over 2 calls.
I should get 2 different random numbers. Can someone please point out my mistake?
Thanks
Khoon.
/* Generation of Random Numbers over a User Defined Range.*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int GenRndNum (int x, int y);

int main (void)

{
int MinRange;
int MaxRange;

int RndNum1;
int RndNum2;

printf ("Please key in the Minimum and Maximum Value for the Range of the two ");
printf ("\nrandom numbers> ");
scanf ( "%d %d", &MinRange, &MaxRange);
RndNum1= GenRndNum (MinRange, MaxRange);
printf ("RndNum1 = %d\n",RndNum1);

RndNum2= GenRndNum (MinRange, MaxRange);
printf ("RndNum2 = %d\n",RndNum2);

return 0;
}

int GenRndNum (int x, int y )

{ int z;
srand (time(NULL));
printf ("x = %d, y = %d\n",x,y);

z = rand() % ((y+1 ) - x ) + x;
printf ("z = %d\n",z);

return (z);
}
/*-----------------------
Result of Output:

Please key in the Minimum and Maximum Value for the Range of the two
random numbers> 2 10
x = 2, y = 10
z = 5
RndNum1 = 5
x = 2, y = 10
z = 5
RndNum2 = 5
Press any key to continue_
*/
Nov 15 '05 #1
23 1739
Red Dragon wrote:
I am self study C program student.
Hope someone can help me with this problem.

<snip>

Please do not post HTML to Usenet. Many clients can't handle this and
even those who can have trouble converting it to text when replying.

You're using Outlook Express. To change the format, choose Tools ->
Options, click on the Send tab, and make sure the radio button "Plain
Text" is on for "News Sending Format".

Rest of the message ignored, sorry.

S.
Nov 15 '05 #2
Red Dragon wrote:
[...]
The problem is that I get the same 2 random numbers generated over 2 calls.
I should get 2 different random numbers. Can someone please point out my mistake?
[...]
int GenRndNum (int x, int y )

{ int z;
srand (time(NULL));
Here it is. See Question 13.17 in the comp.lang.c
Frequently Asked Questions (FAQ) list at

http://www.eskimo.com/~scs/C-faq/top.html

In fact, see all of Questions 13.15 through 13.20; there
are a few other problems with what you're doing, and the
FAQ can help you solve them.
printf ("x = %d, y = %d\n",x,y);

z = rand() % ((y+1 ) - x ) + x;
printf ("z = %d\n",z);

return (z);
}


--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 15 '05 #3
you are using always the same srand value. try this:

long tm;
time(&tm);
srand(tm);

Nov 15 '05 #4
or*****@gmail.com wrote:
you are using always the same srand value. try this:


It is proper Usenet etiquette to include the relevant portions of the text
you are replying to. To do this using Google groups, please follow the
instructions below, penned by Keith Thompson:

If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
Nov 15 '05 #5


or*****@gmail.com wrote On 10/13/05 12:55,:
you are using always the same srand value. try this:
Do NOT try this!
long tm;
time(&tm);
srand(tm);


Reason: The argument to time(), if non-NULL, must be
a pointer to a `time_t' object. `time_t' and `long'
are not necessarily the same thing. If you lie to
the compiler, it will get its revenge.

--
Er*********@sun.com

Nov 15 '05 #6
"Red Dragon" <ts*****@streamyx.com> wrote in
news:43**********@news.tm.net.my:

I am self study C program student.
Hope someone can help me with this problem.
This program generates random numbers over a user defined range using
call function I used the call function " GenRndNum". The range is 2
and 10. The problem is that I get the same 2 random numbers generated
over 2 calls. I should get 2 different random numbers. Can someone
please point out my mistake? Thanks
Khoon.
/* Generation of Random Numbers over a User Defined Range.*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int GenRndNum (int x, int y);

int main (void)

{
int MinRange;
int MaxRange;

int RndNum1;
int RndNum2;

printf ("Please key in the Minimum and Maximum Value for the
Range of the two "); printf ("\nrandom numbers> ");
scanf ( "%d %d", &MinRange, &MaxRange);
RndNum1= GenRndNum (MinRange, MaxRange);
printf ("RndNum1 = %d\n",RndNum1);

RndNum2= GenRndNum (MinRange, MaxRange);
printf ("RndNum2 = %d\n",RndNum2);

return 0;
}

int GenRndNum (int x, int y )

{ int z;
srand (time(NULL));
printf ("x = %d, y = %d\n",x,y);

z = rand() % ((y+1 ) - x ) + x;
printf ("z = %d\n",z);

return (z);
}
/*-----------------------
Result of Output:

Please key in the Minimum and Maximum Value for the Range of the two
random numbers> 2 10
x = 2, y = 10
z = 5
RndNum1 = 5
x = 2, y = 10
z = 5
RndNum2 = 5
Press any key to continue_
*/


Less than a second passes between the two calls to time(), so it's
returning rhe same value to srand() each time.

One way to fix this would be to put a 1-second delay in between the calls
to GenRndNum. Some compilers support a sleep() function. If yours
doesn't, then this code will provide a 1-second delay:

time_t t;
t = time(NULL);
while(time(NULL) <= t);

Put it in GenRndNum(), right before the call to srand(). This will
guarantee that srand() will always get a different seed value.
Nov 15 '05 #7
In article <11**********************@f14g2000cwb.googlegroups .com>,
<or*****@gmail.com> wrote:

you are using always the same srand value. try this:

long tm; /* should be time_t as pointed out by another helpful person */
time(&tm);
srand(tm);


Aside from being wrong (as if this weren't enough) this
approach to seeding a random number generator opens up a
form of attack where two instances of the program are
started at the same time. One instance is used to observe
the seed, the second is manipulated by the user based on
his knowledge of the seed obtained from the first
instance.

For example, two instances of a card playing program
started at once would have the same sequence of cards
generated. The user could anticipate each card and play
the 2nd instance with complete knowledge of the cards
before they appear. In many card games this gives an
advantage.

There are many ways to solve this problem, however most of
them rely on OS-specific features. Of course, whatever you
do can be undone by a hacker willing to modify the program,
e.g. overwriting the call to srand() with a NO-OP
instruction.
Nov 15 '05 #8

"Anonymous 7843" <an******@example.com> wrote in message
news:0rx3f.2024$i%.1492@fed1read07...
In article <11**********************@f14g2000cwb.googlegroups .com>,
<or*****@gmail.com> wrote:

you are using always the same srand value. try this:

long tm; /* should be time_t as pointed out by another helpful person */ time(&tm);
srand(tm);


Aside from being wrong (as if this weren't enough) this
approach to seeding a random number generator opens up a
form of attack where two instances of the program are
started at the same time. One instance is used to observe
the seed, the second is manipulated by the user based on
his knowledge of the seed obtained from the first
instance.

For example, two instances of a card playing program
started at once would have the same sequence of cards
generated. The user could anticipate each card and play
the 2nd instance with complete knowledge of the cards
before they appear. In many card games this gives an
advantage.

There are many ways to solve this problem, however most of
them rely on OS-specific features. Of course, whatever you
do can be undone by a hacker willing to modify the program,
e.g. overwriting the call to srand() with a NO-OP
instruction.


OT As all of this has been. If you have a system in which this is a
concern, you have much bigger security among other, concerns than a
pseudo-random number generator
Nov 15 '05 #9
Eric Sosman <er*********@sun.com> writes:
or*****@gmail.com wrote On 10/13/05 12:55,:
you are using always the same srand value. try this:


Do NOT try this!
long tm;
time(&tm);
srand(tm);


Reason: The argument to time(), if non-NULL, must be
a pointer to a `time_t' object. `time_t' and `long'
are not necessarily the same thing. If you lie to
the compiler, it will get its revenge.


This shouldn't be a case of lying to the compiler. If time_t happens
to be long, the code will work (though of course it's non-portable).
If time_t isn't long, the compiler *should* issue a diagnostic on the
call to time(), something like "passing arg 1 of `time' from
incompatible pointer type".

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #10
Barry wrote:
[...]
long tm; /* should be time_t as pointed out by another helpful person */
time(&tm);
srand(tm);
Aside from being wrong (as if this weren't enough) this
approach to seeding a random number generator opens up a
form of attack where two instances of the program are
started at the same time. One instance is used to observe
the seed, the second is manipulated by the user based on
his knowledge of the seed obtained from the first
instance.

For example, two instances of a card playing program
started at once would have the same sequence of cards
generated. The user could anticipate each card and play
the 2nd instance with complete knowledge of the cards
before they appear. In many card games this gives an
advantage.

[...]
OT As all of this has been. If you have a system in which this is a
concern, you have much bigger security among other, concerns than a
pseudo-random number generator


And, for anyone who doubts that knowledge of a PRNG doesn't give someone
an advantage, search for "Ronald Harris".

http://www.brainboost.com/search.asp...eat+at+keno%3F
Short version of the story:

Ronald Harris worked for the Las Vegas Gaming Commission, and was one of
the people who would verify the "honesty" of computer gaming machines.
(Such as the video poker machines all over the place.) He had access to
the source code for the Keno program used at Bally's Atlantic City, and
was able to create a program that, given a sequence of numbers generated
by the Keno computer, was able to give a pretty good guess as to the next
numbers to be picked. (This included the numbers for the _next_ game, as
well.)

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>

Nov 15 '05 #11
Keith Thompson <ks***@mib.org> writes:
Eric Sosman <er*********@sun.com> writes:
or*****@gmail.com wrote On 10/13/05 12:55,:
you are using always the same srand value. try this:


Do NOT try this!
long tm;
time(&tm);
srand(tm);


Reason: The argument to time(), if non-NULL, must be
a pointer to a `time_t' object. `time_t' and `long'
are not necessarily the same thing. If you lie to
the compiler, it will get its revenge.


This shouldn't be a case of lying to the compiler. If time_t happens
to be long, the code will work (though of course it's non-portable).
If time_t isn't long, the compiler *should* issue a diagnostic on the
call to time(), something like "passing arg 1 of `time' from
incompatible pointer type".


More precisely, it is (conditionally) lying to the compiler, but the
compiler shouldn't be fooled (a diagnostic is required).

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #12

"Kenneth Brody" <ke******@spamcop.net> wrote in message
news:43***************@spamcop.net...
Barry wrote:
[...]
> long tm; /* should be time_t as pointed out by another helpful person */ > time(&tm);
> srand(tm);

Aside from being wrong (as if this weren't enough) this
approach to seeding a random number generator opens up a
form of attack where two instances of the program are
started at the same time. One instance is used to observe
the seed, the second is manipulated by the user based on
his knowledge of the seed obtained from the first
instance.

For example, two instances of a card playing program
started at once would have the same sequence of cards
generated. The user could anticipate each card and play
the 2nd instance with complete knowledge of the cards
before they appear. In many card games this gives an
advantage.
[...]

OT As all of this has been. If you have a system in which this is a
concern, you have much bigger security among other, concerns than a
pseudo-random number generator


And, for anyone who doubts that knowledge of a PRNG doesn't give someone
an advantage, search for "Ronald Harris".

http://www.brainboost.com/search.asp...eat+at+keno%3F

Short version of the story:

Ronald Harris worked for the Las Vegas Gaming Commission, and was one of
the people who would verify the "honesty" of computer gaming machines.
(Such as the video poker machines all over the place.) He had access to
the source code for the Keno program used at Bally's Atlantic City, and
was able to create a program that, given a sequence of numbers generated
by the Keno computer, was able to give a pretty good guess as to the next
numbers to be picked. (This included the numbers for the _next_ game, as
well.)

An interesting read, thanks for the link.
Barry
Nov 15 '05 #13

"Skarmander" <in*****@dontmailme.com> wrote in message
news:43***********************@news.xs4all.nl...
Red Dragon wrote:
I am self study C program student.
Hope someone can help me with this problem.

<snip>

Please do not post HTML to Usenet. Many clients can't handle this and even
those who can have trouble converting it to text when replying.

You're using Outlook Express. To change the format, choose Tools ->
Options, click on the Send tab, and make sure the radio button "Plain
Text" is on for "News Sending Format".

Rest of the message ignored, sorry.

S.


Thank you for your advice. Yes I am using Outlook Express. I did not know
I had caused a problem. Sorry for that.
Rgds,
Khoon.

Nov 15 '05 #14

"Eric Sosman" <es*****@acm-dot-org.invalid> wrote in message
news:7b********************@comcast.com...
Red Dragon wrote:
[...]
The problem is that I get the same 2 random numbers generated over 2
calls.
I should get 2 different random numbers. Can someone please point out
my mistake?
[...]
int GenRndNum (int x, int y )

{ int z;
srand (time(NULL));


Here it is. See Question 13.17 in the comp.lang.c
Frequently Asked Questions (FAQ) list at

http://www.eskimo.com/~scs/C-faq/top.html


Thanks for your advice. Very useful and informative tips.
Rgds,
Khoon.
Nov 15 '05 #15
> Less than a second passes between the two calls to time(), so it's
returning rhe same value to srand() each time.

One way to fix this would be to put a 1-second delay in between the calls
to GenRndNum. Some compilers support a sleep() function. If yours
doesn't, then this code will provide a 1-second delay:

time_t t;
t = time(NULL);
while(time(NULL) <= t);

Put it in GenRndNum(), right before the call to srand(). This will
guarantee that srand() will always get a different seed value.


The strangest thing is that this problem only occurs when I do the
funcion call.
When I rewrite and did the random number generation inside the main
program itself, (and not utilising function call,) I did get two
different random nuimbers. So the problem due to time delay does not appear
to be the cause of the problem.

Rgds,
Khoon.
Nov 15 '05 #16
Red Dragon wrote:
Put it in GenRndNum(), right before the call to srand(). This will
guarantee that srand() will always get a different seed value.

You don't need to call srand() more than once in your program, anyway.
Once the seed is set, just call rand() as often as you need it - it will
create a series of (pseudo-)random numbers.
The strangest thing is that this problem only occurs when I do the
funcion call.
When I rewrite and did the random number generation inside the main
program itself, (and not utilising function call,) I did get two
different random nuimbers. So the problem due to time delay does not
appear to be the cause of the problem.


That's strange indeed. Did you call srand() here twice as well? And did
id happen each time? Maybe the system time really changed in between the
srand() calls.

Best regards
Steffen

Nov 15 '05 #17
> That's strange indeed. Did you call srand() here twice as well? And did
id happen each time? Maybe the system time really changed in between the
srand() calls.

Best regards
Steffen


Yes. Twice as well. In testing every time the rewritten program, I got 2
different random numbers.
No problem about it here. Here is the program. You can test it yourself.
The failure to generate different random numbers occurs only when I tried
function call.
I have set my Outlook Express to Skarmander's instruction, so hope you will
not be getting HTML format.
Thanks,
Khoon.

/* Generation of Random Numbers over a range.
13.10.05 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main (void)

{
int MinRange;
int MaxRange;

int RndNum1;
int RndNum2;

printf ("Please key in the Minimum and Maximum Value for the Range of the
two ");
printf ("random numbers>" );
scanf ( "%d %d", &MinRange, &MaxRange);

srand (time (NULL));

RndNum1 = rand() % ((MaxRange +1 ) - MinRange ) + MinRange;
RndNum2 = rand() % ((MaxRange +1 ) - MinRange ) + MinRange;

printf ("Two random numbers generated are %d & %d\n ", RndNum1,
RndNum2);

return 0;
}


Nov 15 '05 #18
"Red Dragon" <ts*****@streamyx.com> writes:
That's strange indeed. Did you call srand() here twice as well? And did
id happen each time? Maybe the system time really changed in between the
srand() calls.
[...]
Yes. Twice as well. In testing every time the rewritten program, I got 2
different random numbers.
No problem about it here. Here is the program. You can test it yourself.
The failure to generate different random numbers occurs only when I tried
function call. [...]
/* Generation of Random Numbers over a range.
13.10.05 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main (void)

{
int MinRange;
int MaxRange;

int RndNum1;
int RndNum2;

printf ("Please key in the Minimum and Maximum Value for the Range of the
two ");
printf ("random numbers>" );
scanf ( "%d %d", &MinRange, &MaxRange);

srand (time (NULL));

RndNum1 = rand() % ((MaxRange +1 ) - MinRange ) + MinRange;
RndNum2 = rand() % ((MaxRange +1 ) - MinRange ) + MinRange;

printf ("Two random numbers generated are %d & %d\n ", RndNum1,
RndNum2);

return 0;
}


In your original program, upthread, you call srand() withing
GenRndNum(), and you call GenRndNum() in main() -- thus two calls to
srand(). Since the value returned by time(NULL) is unlikely to change
between the two calls, it's not surprising that you'd get the same
"random" number twice. (It's also a bug; srand() should normally be
called only once in a given program, unless you're deliberately
recreating the same sequence multiple times.)

In the program you posted here, in spite of what you wrote above,
there's only one call to srand().

If you change your original program (the one with the GenRndNum()
function) so it calls srand() once in main(), rather than calling it
from GenRndNum(), it should do what you want.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #19
> In your original program, upthread, you call srand() withing
GenRndNum(), and you call GenRndNum() in main() -- thus two calls to
srand(). Since the value returned by time(NULL) is unlikely to change
between the two calls, it's not surprising that you'd get the same
"random" number twice. (It's also a bug; srand() should normally be
called only once in a given program, unless you're deliberately
recreating the same sequence multiple times.)

In the program you posted here, in spite of what you wrote above,
there's only one call to srand().

If you change your original program (the one with the GenRndNum()
function) so it calls srand() once in main(), rather than calling it
from GenRndNum(), it should do what you want.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.

Good news.
Problem solved.
Earlier I did not understand the passing of data and wrote the program wrongly.
I have now discovered my error in the structure of the program writing.
Now I have rewritten and the program is working perfectly. I am getting 2 different random numbers each time now.

So the srand() seeding thing got blamed for nothing.

Here is my correct program.
Rgds,
Khoon.

/* Generation of Random Numbers over a User Defined Range with Function.
15.10.05 */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void GenRndNum (int x, int y, int *RndNum1, int *RndNum2);
int main (void)

{
int MinRange;
int MaxRange;

int RndNum1;
int RndNum2;


printf ("Please key in the Minimum and Maximum Value for the Range of the two ");
printf ("\nrandom numbers> ");
scanf ( "%d %d", &MinRange, &MaxRange);
printf ( "MinRange =%d , MaxRange = %d\n", MinRange,MaxRange);
GenRndNum (MinRange, MaxRange, &RndNum1, &RndNum2);
printf ("RndNum1 = %d, RndNum2= %d\n",RndNum1,RndNum2);

return 0;
}
void GenRndNum (int x, int y, int *RndNum1,int *RndNum2)

{
srand (time (NULL));
*RndNum1 = rand() % ((y+1 ) - x ) + x;
*RndNum2 = rand() % ((y+1 ) - x ) + x;
return ;
}

Nov 15 '05 #20
Red Dragon wrote:
Good news.
Problem solved.
Earlier I did not understand the passing of data and wrote the
program wrongly.
I have now discovered my error in the structure of the program
writing.
Now I have rewritten and the program is working perfectly. I am
getting 2 different random numbers each time now.

So the srand() seeding thing got blamed for nothing.


Maybe someday you'll understand about srand too.

--
pete
Nov 15 '05 #21

Good news.
Problem solved.
Earlier I did not understand the passing of data and wrote the program wrongly.
I have now discovered my error in the structure of the program writing.
Now I have rewritten and the program is working perfectly. I am getting 2 different random numbers each time now.

So the srand() seeding thing got blamed for nothing.

Here is my correct program.
Rgds,
Khoon.
Correction,
Actually, srand has got problem as rightly pointed out and also as stated in the Q&A as seen below. In fact the authority does not recommend to call srand more than once during a run of a program which I dont understand why.

Rgds,
Khoon.

Question 13.17
Each time I run my program, I get the same sequence of numbers back from rand().
------------------------------------------------------------------------------

You can call srand to seed the pseudo-random number generator with a truly random initial value. Popular seed values are the time of day, or the elapsed time before the user presses a key (although keypress times are hard to determine portably; see question 19.37). (Note also that it's rarely useful to call srand more than once during a run of a program; in particular, don't try calling srand before each call to rand, in an attempt to get ``really random'' numbers.)

References: K&R2 Sec. 7.8.7 p. 168
ANSI Sec. 4.10.2.2
ISO Sec. 7.10.2.2
H&S Sec. 17.7 p. 393

------------------------------------------------------------------------------

Read sequentially: prev next up top
------------------------------------------------------------------------------

This page by Steve Summit // Copyright 1995 // mail feedback

Nov 15 '05 #22
"Red Dragon" <ts*****@streamyx.com> wrote in message
news:43********@news.tm.net.my...
Good news.
Problem solved.
No, you've just given the system time a chance to change between runs.
So the srand() seeding thing got blamed for nothing.


No, it *IS* the problem. As others have noted, srand seeds the random number
generator. It'll do it every time it's called. If you seed with the same
number, you'll get the same results to rand() calls. If you call it fast
enough, the system time will be the same for subsequent calls an the sequence
will repeat.

Try this:

/*
* Version to demonstrate problem with srand() call
* Based on:
* Generation of Random Numbers over a User Defined Range with
* Function.15.10.05
*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void GenRndNum (int x, int y, int *RndNum1, int *RndNum2);
int main (void)

{
int MinRange;
int MaxRange;

int RndNum1;
int RndNum2;

int i;

/*
* DEBUG Set range directly, don't give system time a chance to change
*
printf ("Please key in the Minimum and Maximum Value for the"
" Range of the two ");
printf ("\nrandom numbers> ");
scanf ( "%d %d", &MinRange, &MaxRange);
*/
MinRange = 1;
MaxRange = 10;
printf ( "MinRange =%d , MaxRange = %d\n", MinRange,MaxRange);

/* DEBUG and do it a several times */
for (i = 0; i < 5; i++)
{
GenRndNum (MinRange, MaxRange, &RndNum1, &RndNum2);
printf ("RndNum1 = %d, RndNum2= %d\n",RndNum1,RndNum2);
}
return 0;
}
void GenRndNum (int x, int y, int *RndNum1,int *RndNum2)
{
srand (time (NULL));
*RndNum1 = rand() % ((y+1 ) - x ) + x;
*RndNum2 = rand() % ((y+1 ) - x ) + x;
return ;
}

Here's the results:

C:\>x
MinRange =1 , MaxRange = 10
RndNum1 = 2, RndNum2= 3
RndNum1 = 2, RndNum2= 3
RndNum1 = 2, RndNum2= 3
RndNum1 = 2, RndNum2= 3
RndNum1 = 2, RndNum2= 3

But, if you call srand() only once, like this (or any number of other ways to
do it only once):

void GenRndNum (int x, int y, int *RndNum1,int *RndNum2)
{
static int run_once = 1;

if (run_once)
{
srand (time (NULL));
run_once = 0;
}
*RndNum1 = rand() % ((y+1 ) - x ) + x;
*RndNum2 = rand() % ((y+1 ) - x ) + x;
return ;
}

The results are:

C:\>x
MinRange =1 , MaxRange = 10
RndNum1 = 9, RndNum2= 2
RndNum1 = 10, RndNum2= 3
RndNum1 = 8, RndNum2= 1
RndNum1 = 4, RndNum2= 9
RndNum1 = 8, RndNum2= 6

If efficiency matters, then doing the srand() call in main (or somewhere else
executed only once per program run) will work better. Doing something like the
above hides srand() from the main program (possibly an advantage) and ensure
that it's called at least the once needed. The downside is that the test to
see if it's been done gets executed for every single invocation of GetRndNum.
I did it this way above mostly to keep from re-quoting the entire program just
to move srand() out of the function.

- Bill
Nov 15 '05 #23
>
The results are:

C:\>x
MinRange =1 , MaxRange = 10
RndNum1 = 9, RndNum2= 2
RndNum1 = 10, RndNum2= 3
RndNum1 = 8, RndNum2= 1
RndNum1 = 4, RndNum2= 9
RndNum1 = 8, RndNum2= 6

If efficiency matters, then doing the srand() call in main (or somewhere
else
executed only once per program run) will work better. Doing something
like the
above hides srand() from the main program (possibly an advantage) and
ensure
that it's called at least the once needed. The downside is that the test
to
see if it's been done gets executed for every single invocation of
GetRndNum.
I did it this way above mostly to keep from re-quoting the entire program
just
to move srand() out of the function.

- Bill

Thanks Bill,
I can see that you are an expert in this field. I tried and it worked
exactly as what you have explained. I have benefited greatly from your
contribution and others too.
Very grateful that you have come in to clear the haze.
Regards,
Khoon.

Nov 15 '05 #24

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

Similar topics

3
by: Paul T. Rong | last post by:
Dear all, My aim is to compact and repair current database, I got the following code from http://www.mvps.org/access/general/gen0041.htm Option Compare Database ' ***** Code Start *****...
15
by: Paul T. RONG | last post by:
Hello, I am making a restaurant database (it is much more complicated than I thought before!), now it comes to the last stage and I come across a problem. I will explain it in detail. In a...
25
by: Nikola | last post by:
compiler says: function undeclared how come??? help! #include<stdio.h> #include<stdlib.h> #include<time.h> struct lista{ int element; struct lista *next; }*pocetak;
3
by: bughunter | last post by:
IMHO, statements like this is mistake typically. May be more better made this construction - I said about empty WHERE - invalid? A lot of data will saved... :-) Andy
2
by: Lad | last post by:
I use the following code to sort dictionary. Olddict={'r':4,'c':1,'d':2,'e':3,'f':2} Newdict={} i = i.sort() # by val i.reverse() # Get largest first. for (val, key) in i: print key,val
20
by: Frank-O | last post by:
Hi , Recently I have been commited to the task of "translating" some complex statistical algorithms from Matlab to C++. The goal is to be three times as fast as matlab ( the latest) . I've...
4
by: Winston | last post by:
Where is the mistake? I want to make a simple menu. These are two pieces of two files... function ShowMenu(objeto) { is_open = document.getElementById(objeto).style.display;...
4
by: | last post by:
I have learned about compartmentalizing my code base using Class Libraries. I have my common code such as my ORM framework broken out into their own Class Libraries, which are referenced as...
2
by: Eglute | last post by:
Hello. I have a problem. I am a begginer in PHP. I wrote the code: <? $variable=5; $variable<10? {$ans="less"; echo $ans."<br>"; echo "variable=".$variable."<br>";}: ...
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.