TaeHyun. A - 1 year ago 70
Java Question

# Integer Divisions are not outputting correct answers - Java

I have created a simple program to test a few things.

Piece of the code:

``````int n = 250 * (50 / 500) + 50;
System.out.println(n);
``````

I have expected the program to output
`75`
, but instead, it outputs
`50`

So I have 2 questions:

1. Why does it output
`50`
`75`
?

2. Are there any ways so that it outputs
`75`
?

Any help is appreciated happily,

Why does it output `50` instead of `75`?

It's because 50 / 500 is 0.1, but since its integer division, it becomes 0 as the fractional part is cut off. It then multiplies 250 and 0, resulting in 0, then adding 50, thus yielding 50.

Are there any ways so that it outputs `75`?

``````int n = 250 * 50 / 500 + 50;
System.out.println(n);
``````

The above will take 250 and multiply by 50 yielding 12500. Next it will do 12500 / 500, which results in 25. Lastly, it will add 25 and 50, resulting in 75.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download