0

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

Paul R
  • 208,748
  • 37
  • 389
  • 560
user1779429
  • 65
  • 1
  • 2
  • 3
  • 5
    You are using changeY/*changeZ* in the example above instead of *changeX*. Are you sure that's correct? – Theocharis K. Nov 26 '12 at 10:54
  • 2
    Because you are doing something wrong. However, we cannot tell you exactly what it is, with this little information. Give a minimal, yet complete code example, where we see the declarations and definitions of `changeX` etc. and the calculation of `slope`. – Good Night Nerd Pride Nov 26 '12 at 11:02
  • @Alberto: no - this is not needed - the OP's code with the cast should work as expected. The problem lies elsewhere. – Paul R Nov 26 '12 at 11:26
  • 1
    What is `changeZ`, the value you're dividing by? If that is large enough, the result will be small enough to be displayed as `0.000000` with `printf("%f\n", slope);`. – Daniel Fischer Nov 26 '12 at 11:51
  • Maybe changeZ if close or equal to infinity. – Ramy Al Zuhouri Nov 26 '12 at 11:52
  • Possible duplicate of [Integer division always zero](https://stackoverflow.com/q/9455271/608639) – jww Oct 24 '18 at 10:02

1 Answers1

12

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.
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
Lundin
  • 195,001
  • 40
  • 254
  • 396
  • +1: not sure why this got an immediate down-vote - it's the closest thing we have to a correct answer so far ? – Paul R Nov 26 '12 at 12:07
  • Note that *slope* is more likely to be `changeY/changeX`. – Paul R Nov 26 '12 at 12:09
  • 1
    @PaulR Ah yeah, probably. Thanks, I'll edit (even though it isn't related to the particular issue). – Lundin Nov 26 '12 at 12:11
  • Well if we're going to guess what the problem is we might as well use the best possible guess given the limited data. ;-) – Paul R Nov 26 '12 at 12:12
  • 1
    The answer states the result of division is a double. The result is semantically a double but may actually have more precision. – Eric Postpischil Nov 26 '12 at 14:18