Date: Mon, 6 Jan 1997 19:38:43 +0200 (IST) From: Eli Zaretskii To: "M.M. Span" <ļi4 AT is DOT elta DOT co DOT il> cc: djgpp AT delorie DOT com Subject: Re: floats and ints In-Reply-To: <5ar6pi$8go@info.service.rug.nl> Message-ID: MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII On 6 Jan 1997, M.M. Span wrote: > 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. It's a feature. When you divide two ints, you get integer division. The compiler couldn't care less about the type of the variable to which you assign the result of the division. To get float division, it is enough to cast only one of the variables to floating point; you don't need to cast both of them. Btw, I suggest you use double instead of float as a general rule, unless you are VERY tight on memory and need LARGE arrays of floating numbers. x86 CPUs do all floating point operations in the internal 80-bit format anyway, so you don't gain any speed by using floats. You *do* lose a lot of accuracy.