[thelist] unexpected c++ casting double to integer behaviour

Rob Agar robagar at westnet.com.au
Fri Sep 1 21:10:31 CDT 2006


hi Bernardo,

Perhaps rather than an integer cast, you need to round the value? 
Casting a double to an int just discards everything after the decimal point.

hth
Rob

Bernardo Escalona-Espinosa wrote:
> Hello List!
> 
> I am really desperate. I need to finish this by monday so I hope some
> of you are home to see this.
> 
> I have the following loop:
> 
> ===================
>     double step = 0.05;
>     double stop = 4.0;
> 
>     int numerator = 4;
>     int denominator = 4;
> 
>     int x = 0;
>     int y = 0;
>     int z = 0;
> 
>     double beat;
>     double tmp;
> 
>     for(beat=0.0; beat<=stop; beat+=step){
> 
>       x = int(int(beat)/numerator) + 1;
>       y = int(beat)%numerator + 1;
>       tmp = 10*(beat - int(beat))/2.50 + 1.0;
>       z = int(tmp);
> 
>       cout << beat << "\t" << x << "." << y << "." << z << "\t" << tmp << endl;
>     }
> ===================
> 
> Maybe it looks like too much for a friday evening but the problem just
> lies in the difference between the variables "tmp" and "z".
> 
> Sometimes the operation "int(tmp)" produces unexpected results. The
> following iteration from the output shows my problem:
>  2.5     1.3.2     3
> (beat   x.y.z    tmp)
> 
> As you can see, while "tmp" has the value of 3, (or at least, it is
> showing up as 3... i am beginning to think its more like 2.999...) the
> variable "z" is 2. What can I do about this?
> 
> I'm compiling with Dev-C++ on a WinXP SP1 Pentium4.
> 
> 
> 




More information about the thelist mailing list