|
What are the rules for deciding whether a division is integer, or float? |
Chris Katko
Member #1,881
January 2002
|
int NUM_POINTS = 200; int c = 255 - (i/NUM_POINTS*255); //clearly integer int c = 255 - (i/NUM_POINTS*255.0); // apparently NOT float int c = 255 - ((float)i/NUM_POINTS*255.0); // float int c = 255 - (float)(i/NUM_POINTS*255.0); // not float The second one surprised me. -----sig: |
Erin Maus
Member #7,537
July 2006
|
Why would it be surprising? If i is an integer and NUM_POINTS is an integer, then of course it will be integer division. --- |
Elias
Member #358
May 2000
|
Automatic conversions are per operation. Since the / has precedence over *, i/NUM_POINTS*255.0 is the same as (i/NUM_POINTS)*255.0. And so the first operation is: i/NUM_POINTS, with both operands integer, so an integer division is performed. -- |
duncan perham
Member #15,403
November 2013
|
Personally I do it like this, makes it easier to read and easily see whats going on. int c = 255 - (((float)i/NUM_POINTS)*255.0); |
Bruce Perry
Member #270
April 2000
|
If I wanted a float in the end, I might do it like this to give the compiler no doubt about whether it's allowed to rewrite it this way for efficiency (note I'm assuming NUM_POINTS is constant, given the capitals, and I would have done it as a #define to make sure): float c = 255 - i*(255.0f/NUM_POINTS); However, in this example, we clearly want an int, so it's sacrilege to venture into slower types with slightly unspecified behaviour for no reason (not to mention leaving it to an implicit cast to take care of converting back again) int c = 255 - i*255/NUM_POINTS; -- |
Kitty Cat
Member #2,815
October 2002
|
Elias said: Since the / has precedence over * They actually have equal precedence. In this case, it's evaluated left-to-right with standard math rules (PEMDAS; parenthesis, exponent, multiply and divide, addition and subtraction). -- |
|