user1779429
user1779429

Reputation: 65

casting integer division into double in C

Why does the code

double slope = (double)changeY/changeZ 

set slope to 0.0, when in the program I have, changeX = 20 and changeY = 10 (both ints)?

Upvotes: 0

Views: 20176

Answers (1)

Lundin
Lundin

Reputation: 215115

It sounds like you are using the wrong variable. Try this:

int changeX = 20;
int changeY = 10;

double slope = (double)changeY/changeX;

The cast operator () has higher priority than /. This expression will get evaluated as:

  • Cast changeY to a double.
  • Implicitly convert changeX to a double. If one operand is double, then the other operand gets balanced to a double as well (this is formally called "the usual arithmetic conversions").
  • Divide the two operands. The result will be a double.
  • Store this temporary "result-double" into another double called slope.

Upvotes: 12

Related Questions