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

Bernardo Escalona-Espinosa escalonab at gmail.com
Fri Sep 1 14:23:45 CDT 2006


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.



-- 
___________________________________________
Bernardo Escalona Espinosa
  handy: 0176 / 24 82 35 34
  http://www.bernsonline.com/



More information about the thelist mailing list