Why is it when I do two operations with integer numbers and save the result in a double it gives me a 0.0 return?

Asked

Viewed 83 times

0

Example:

double teste = 673/5455 * 100;

System.out.println(teste);  

It prints 0.0 and this is not the result of the account... why it happens?

  • 3

    How much is the integer 673 divided by the integer 5455?

  • 2

    So you need to come back and learn math.

  • No league Aline.

  • ...okay Fábio =)

1 answer

5


As the question itself says it is dividing two integers, so the result will be an integer. If dividing 673 by 5455 will obviously give a value less than 1 since the divisor is greater than the dividend, in fact it will be below 0,5 and as it can only work with integer it rounds to 0, then multiplying by 100 continues giving 0 and keeps the 0 in variable.

If you want to settle, make one of them double, for example 673.0.

class Main {
    public static void main (String[] args) {
        double teste = 673.0 / 5455 * 100;
        System.out.println(teste);  
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Hummmm. I already knew how to solve this just didn’t understand why it happened now you explained. So tbm goes: double test =(double) 673/5455 * 100;

  • Now I understand!!!

  • Yes, the cast works, but already putting the correct literal is better

Browser other questions tagged

You are not signed in. Login or sign up in order to post.