0
I cannot understand why you are giving 0.00 for the calculation, and if I change the order of the calculation of the expected value, the calculation has only division and multiplication.
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n, i, animal, total = 0, totalRato = 0, totalSapo = 0, totalCoelho = 0;
double percentualCoelhos, percentualRatos, percentualSapos;
char categoriaAnimal;
Locale.setDefault(Locale.US);
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for (i = 0; i < n; i++) {
animal = sc.nextInt();
categoriaAnimal = sc.next().charAt(0);
if (categoriaAnimal == 'R') {
total += animal;
totalRato += animal;
}
else if (categoriaAnimal == 'S') {
total += animal;
totalSapo += animal;
}
else if (categoriaAnimal == 'C') {
total += animal;
totalCoelho += animal;
}
}
sc.close();
percentualCoelhos = totalCoelho * 100.0 / total;
percentualRatos = totalRato / total * 100.0;
percentualSapos = totalSapo / total * 100.0;
System.out.println("Total: " + total + " cobaias");
System.out.println("Total de coelhos: " + totalCoelho);
System.out.println("Total de ratos: " + totalRato);
System.out.println("Total de sapos: " + totalSapo);
System.out.printf("Percentual de coelhos: %.2f%%%n", percentualCoelhos);
System.out.printf("Percentual de ratos: %.2f%%%n", percentualRatos);
System.out.printf("Percentual de sapos: %.2f%%%n", percentualSapos);
}
}
The problem is in the code percentualCoelhos = totalCoelho * 100.0 / total;
I see no difference in calculating in this way: percentualCoelhos = totalCoelho / total * 100.0;
, but the value of the different. Why?
Because total and total are integers and the division between integers is rounded to zero. If you want the result to be double, cast: https://ideone.com/sYfGXB
– hkotsubo