PlaneShift

Development => Development Deliberation => Topic started by: picobyte on February 10, 2006, 03:47:59 pm

Title: float integer issue
Post by: picobyte on February 10, 2006, 03:47:59 pm
In function csPen:: DrawArc in file pen.cpp (cstool lib) floats and integers are mixed. If you do an integer division like

void csPen:: DrawArc(uint x1, uint x2, ... )
{
  float width = x2-x1;
  float x_radius = width/2;
  ...
}

then, since the 2 is an integer (2.0 is a float), this division will be translated by the compiler to

  float x_radius = (float)( (int)width/2 );

The consequence is that a width of 3 for instance will not evaluate to the float 1.5, but to 1.0 (integer division allways rounds down).
I am not sure what is intended here, but I think either this should be rewritten as:

  float width = x2-x1;
  float x_radius = width/2.0; // evaluates to 1.5

or when intended as:

  int  width = x2-x1;
  int radius = width/2 // which evaluates to 1

both width and radius can in this case be uints even, I think, because if I am correct x2 should allways be greater than x1. (maybe that should be tested beforehand)
Title:
Post by: jorrit on February 10, 2006, 04:15:04 pm
Quote
Originally posted by picobyte
In function csPen:: DrawArc in file pen.cpp (cstool lib) floats and integers are mixed. If you do an integer division like

void csPen:: DrawArc(uint x1, uint x2, ... )
{
  float width = x2-x1;
  float x_radius = width/2;
  ...
}

then, since the 2 is an integer (2.0 is a float), this division will be translated by the compiler to

  float x_radius = (float)( (int)width/2 );


That is not true. The division will be translated by the compiler to:

float x_radius = width / float (2);

The code is correct.

Greetings,
Title:
Post by: jorrit on February 10, 2006, 04:17:21 pm
Try this very simple C program:

int main (int argc, char* argv[])
{
  float width = 3.5;
  float width_2 = width / 2;
  printf (\"width_2=%g\\n\", width_2);
}

When I compile it and run it it outputs:

width_2=1.75

Greetings,
Title:
Post by: picobyte on February 10, 2006, 04:24:21 pm
I thought I read that somewhere, but well, you\'re probably right. :s
Title:
Post by: Bereror on February 10, 2006, 04:33:05 pm
Quote
Originally posted by picobyte
I thought I read that somewhere, but well, you\'re probably right. :s

From the book \"The C++ Programming Language\" written by Bjarne Stroustrup (the creator of C++) Appendix C:

C.6.3 Usual Arithmetic Conversion
... if either operand is double, the other is converted to double.