From: suma AT xtra DOT co DOT nz (Alex Clifford Henderson) Newsgroups: comp.os.msdos.djgpp Subject: Re: floats and ints Date: Thu, 09 Jan 1997 22:37:56 GMT Organization: TWINS Software Lines: 81 Message-ID: <5b52vh$bm42@wolfman.xtra.co.nz> References: <5ar6pi$8go AT info DOT service DOT rug DOT nl> NNTP-Posting-Host: 203.96.101.238 To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp span AT PROBLEM_WITH_INEWS_GATEWAY_FILE (M.M. Span) wrote: >Maybe this is a generic C or C++ question, but I use DJGPP, so why not here? >int main( int argc, char** argv ) >{ >int i=1; >int npoints=500; >float omega = 0.0 >omega = i/npoints; >cout << omega << endl; >return 0; >} >yields: >0 >casting (float)i/(float)npoints; >will yield the correct answer. >is this a bug or a feature. The way I learnt C/C++ (from a TurboC++ 3.0 manual in 1992 no less) was that and integer devided by an integer will return an integer and that: omega=i/npoints; is like having a function to devide integers. omega=int_div(i,npoints); which means you are taking the (float) casting of the integer returned by int_div, which will of course be zero. you must remember 2 things, 1/ that an expression is evaluated on the right side completely before any effect of casting and asigning the value to the left side, the right side know's nothing of the left side until it has finished being evaluated. 2/ any of those simple operators +,-,*,/ will promote to the most acurate or large type present. floating point values overide longs, and doubles overide floats etc. etc. i.e (float) * (int) returns float (long) * (int) return long (float) * (double) returns double where " * " can be substituted for any of the other four simple operators (note: shift-left and shift-right operators dont count, they always take the second argument as an int) so when an integer devides an integer you get.... an integer. of course I dont explain it half as well as the borland Turbo C++ 3.0 manual could :-) BTW are you still learning C/C++ or have you learnt a pigeon form of it (like some Pascal people I know which have 100's of defines which makes C act like pascal for them, though why they would want to I dont know... [sorry for the late posting, I had to pick hay up yesterday] -- //// /'^'\ \\\\ (\0-0/) //// /----------------------------------oOOOO--(_)--OOOOo--\ | Alex Henderson a.k.a Suma | | email: Suma AT xtra DOT co DOT nz (^^\ | \-------------------------------------\ (--|--/^^)----/ \_) | ) / * | (_/ \__/