Reputation: 65
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
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:
changeY
to a double
.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").Upvotes: 12