-1

Could some please offer any insight into why this code is outputting 40? I tried using doubles instead of integers and using the Math.round method to make sure it wasn't a precision issue.

{
    int x,y ;
    x = ((( 80 + 80 + 80 + 80 + 80) / 500) * 100);
    y = ((x / 2) + (80 / 4) + (80 / 4));
    System.out.println(y);
}

I've evaluated the same expression using a calculator and just my own head and on all accounts it should be 80! If I'm making a really dumb mistake I'd like to know but otherwise I'm just curious as to why this is and how to get around it, thanks in advance!

  • 3
    What do you expect the value of `x` to be, and have you checked that part? Hint: all your operations are in terms of integers, and 400/500 is 0 in integer arithmetic... – Jon Skeet Nov 02 '16 at 18:04
  • eventually only `(80 / 4) + (80 / 4)` matters – Pavneet_Singh Nov 02 '16 at 18:05
  • I think @JonSkeet gets it correct here. In Python, x evaluates to zero on account of it being integer arithmetic. – Pat Jones Nov 02 '16 at 18:08

2 Answers2

2

Your x is 0 because:

( 80 + 80 + 80 + 80 + 80) / 500) evaluates to 0.

As a result, y becomes ((0 / 2) + (80 / 4) + (80 / 4)) which evaluates to 40.

Note that when a type int is between 0 and 1, it becomes 0.

Per comment, when evaluating 400 / 500, whether or not x is int or double is not relevant, because 400 and 500 is integer so java will apply int arithmetic first, and then move on.

Minjun Yu
  • 3,497
  • 4
  • 24
  • 39
  • Well that expression would evaluate to 0.8, then be multiplied by 100, making 80. – Aaron Fisher Nov 02 '16 at 18:08
  • @AaronFisher: Why do you think that expression would evaluate to 0.8? See my comment on your question. – Jon Skeet Nov 02 '16 at 18:09
  • @AaronFisher `0.8` is not an integer. Intermediate values need to be stored as well. – nbrooks Nov 02 '16 at 18:09
  • 0.8 is "converted" to 0 and then got multiplied by 100. – Minjun Yu Nov 02 '16 at 18:09
  • Even if I used doubles, like so { double x,y ; x = ((( 80 + 80 + 80 + 80 + 80) / 500) * 100); y = ((x / 2) + (80 / 4) + (80 / 4)); System.out.println(y); } I still only get 40.0, not 80 as I'm expecting – Aaron Fisher Nov 02 '16 at 18:09
  • At least in Python, not sure about Java, you'd need to write 80.0 and 100.0 rather than 80 and 100, which forces the calculation to decimals. – Pat Jones Nov 02 '16 at 18:11
  • @AaronFisher when evaluation 400 / 500, whether or not x is int or double is not relevant, because 400 and 500 is integer so java will apply int arithmetic. – Minjun Yu Nov 02 '16 at 18:11
  • Ohh i see what you're saying @Minjun I'll try switching the values to doubles, thanks all! – Aaron Fisher Nov 02 '16 at 18:13
0

x = ((400)/500))* 100

Here 400/500 evaluates to 0 as 400 and 500 are treated as integers

so y = 0 + (80/4) + (80/4) = 40

hemanth.b
  • 53
  • 5