4

I have the following variables:

int first = 0;
int end = 0;

Declare in the public class.

Within a method:

double diff = end / first;
double finaldiff = 1 - diff;

The end variable on System.out.println is 527, the first is 480.

Why is the answer for diff coming out as 1? It should be 1.097916667, I thought using a double would enable me to calculate into decimals?

Kevin Panko
  • 8,356
  • 19
  • 50
  • 61
  • 0 / 0 is neither 1 nor 1.097916667... – Oliver Charlesworth Apr 29 '12 at 21:55
  • 1
    Sorry, the end and first is gathered within a previous if statement. –  Apr 29 '12 at 21:56
  • @OliCharlesworth: OP states: `The endyear variable on system.out.println is 527, the firstyear is 480.` As such the calculation is 527/480 which deos equal `1.097916666666667`. Not sure where you got 0/0 from. – Nope Apr 29 '12 at 21:59
  • @FrançoisWahl: From the fact that the OP specifies they're both 0... – Oliver Charlesworth Apr 29 '12 at 22:00
  • @OliCharlesworth: Well, it is class-level... – Ry- Apr 29 '12 at 22:00
  • @OliCharlesworth: I suppose all other members not having read past the first section are the ones down voting I guess. +1 from me anyway after reading the whole post. – Nope Apr 29 '12 at 22:03
  • 3
    @FrançoisWahl: I did read the whole question, evidently you read it too quickly (!) - "`endyear`" != "`end`", etc. Anyway, I didn't downvote. – Oliver Charlesworth Apr 29 '12 at 22:04
  • @OliCharlesworth: You are correct in that the names don't match but I simply assumed they were the values though the OP referred to as the error was not related to a null division. But yes, you are correct and taking the post verbatim I see where you are coming from. – Nope Apr 29 '12 at 22:06
  • This is certainly ambiguous at _best_... I think I can understand what the OP is saying, but when I have to assume that `first = firstyear` and `end = endyear` happen before `diff = end / first`, I also have to wonder what else is going on that hasn't been stated. @FrançoisWahl – Pops Apr 29 '12 at 22:07
  • My apologies, i've corrected my explanation. –  Apr 29 '12 at 22:09
  • @LordTorgamus: I see what you saying. I think I just focused on the values being divided and that the issue was a rounding issue not a null division. You are correct in what you saying though that once you are assuming who knows what else is missing. – Nope Apr 29 '12 at 22:31

1 Answers1

5

Dividing two ints will get you an int, which is then implicitly converted to double. Cast one to a double before the divison:

double diff = (double)end / first;
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • 2
    I had to wait ten minutes @lukecampbell, as does everyone when marking an answer correct. –  Apr 29 '12 at 22:08