TIP: Click on subject to list as thread! ANSI
echo: nthelp
to: Geo
from: Paul Ranson
date: 2004-12-10 12:18:26
subject: Re: c++ help

From: "Paul Ranson" 

'rand()/RAND_MAX' will usually evaluate to 0. All integer arithmetic always
works and you never get an exception, that's just how CPUs go.

If you write it as 'rand() * 9999 / RAND_MAX' then the multiplication will
be done first and you'll get a more sensible answer. I'm not convinved
though that the sensible answer will be a random number between 0 and 9999.
But this is nothing to do with C and everything to do with maths.

For values of 'rand()' 0, 1, 2, 3 you'll get 0, for 4, 5, 6 you'll get 1,
for 7, 8, 9 you get 2 etc etc. Work it out on a calculator and conver to
'int' by rounding down.

Paul

"Geo"  wrote in message
news:41b97df5$1{at}w3.nls.net...
> "John Beckett" 
wrote in message
> news:41b92073.3609980{at}216.144.1.254...
>> "Geo"  wrote in message
news::
>
>> > int n = (rand()/32767)*9999999999999
>> >
>> > That shouldn't generate a cpu error, the error would come when it goes
> to
>> > store a multibyte value in a single byte location (or maybe at compile
>> > time?)
>>
>> I don't follow your meaning. If you intend that the
"9999999999999" is
>> too
>> large for an int, the compiler would assume it is a long int. If the
>> value
>> is too large for a long int,
>
> What I was trying to say (and I haven't tested this yet due to lack of
> time)
> is that the computer will evaluate the right side of the above equation
> using 32 bits not 8 bits. If that's true then
>
> int n = (rand()/MAX_RAND)*9999
>
> should come out as
>
> int n = (0.123)*9999
>
> or something greater than 1 and so int n should come out to something
> other
> than zero, no? If not then this would be very limiting for doing anything
> using rand() and an int value since (rand()*9999)/MAX_RAND could also
> evaluate to something that blows int limits (for example if rand() is
> 32000).
>
> Geo.
>
>

--- BBBS/NT v4.01 Flag-5
* Origin: Barktopia BBS Site http://HarborWebs.com:8081 (1:379/45)
SEEN-BY: 633/267 270 5030/786
@PATH: 379/45 1 396/45 106/2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.