Why when I do two operations with integers and save the result in a double it gives me a 0,0 return?

0

Example:

double teste = 673/5455 * 100;

System.out.println(teste);  

It prints 0.0 being that is not the result of the account ... why does this happen?

    
asked by anonymous 12.03.2017 / 17:56

1 answer

4

As the question itself says 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 saves 0 in the variable.

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

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

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

    
12.03.2017 / 18:05