Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » What are the rules for deciding whether a division is integer, or float?

This thread is locked; no one can reply to it. rss feed Print
What are the rules for deciding whether a division is integer, or float?
Chris Katko
Member #1,881
January 2002
avatar

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:
“Programs should be written for people to read, and only incidentally for machines to execute.” - Structure and Interpretation of Computer Programs
"Political Correctness is fascism disguised as manners" --George Carlin

Erin Maus
Member #7,537
July 2006
avatar

Why would it be surprising? If i is an integer and NUM_POINTS is an integer, then of course it will be integer division.

---
ItsyRealm, a quirky 2D/3D RPG where you fight, skill, and explore in a medieval world with horrors unimaginable.
they / she

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.

--
"Either help out or stop whining" - Evert

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;

--
Bruce "entheh" Perry [ Web site | DUMB | Set Up Us The Bomb !!! | Balls ]
Programming should be fun. That's why I hate C and C++.
The brxybrytl has you.

Kitty Cat
Member #2,815
October 2002
avatar

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).

--
"Do not meddle in the affairs of cats, for they are subtle and will pee on your computer." -- Bruce Graham

Go to: