Program with decimals in while

0

I have the following code:

package while2;    
import javax.swing.JOptionPane;

public class While2 {
    public static void main(String[] args) {

        int numero;
        int i=1;
        int suma=0;
        int TotalNumeros=3;
        double promedio= 0;

        while(i<=TotalNumeros) {
            numero= Integer.parseInt(JOptionPane.showInputDialog ("Ingresa el numero"));
            suma= numero+suma;
            i=i+1;      
        }

       promedio= suma/TotalNumeros;         
       JOptionPane.showMessageDialog(null,"El valor total de la suma es: " + suma);
       JOptionPane.showMessageDialog(null, "El promedio es:" + promedio);        
    }    
}

The problem is that the average does not calculate the decimals.

Example: if the answer is 8 the average gives me = 2.0 I did it in Excel and it gives me 2,666666667 .

    
asked by Pupo Xws 11.07.2016 в 23:54
source

1 answer

1

The problem you have is simple, you are using Integer variables to perform the average and how those Integer do not have decimals.

There are several options but the easiest and most direct one that fits your question would be to use a Double that does save decimals.

Simply replace your line with Integer with:

numero = Double.parseDouble(JOptionPane.showInputDialog ("Ingresa el numero"));

And declaring the number numero as Double :

double numero;

So your final code would be:

package while2;    
import javax.swing.JOptionPane;

    public class While2 {
        public static void main(String[] args) {

            double numero;
            double i=1;
            double suma=0;
            double TotalNumeros=3;
            double promedio= 0;

            while(i<=TotalNumeros) {
                double numero; numero= Double.parseDouble(JOptionPane.showInputDialog ("Ingresa el numero"));
                suma= numero+suma;
                i=i+1;      
            }

           promedio= suma/TotalNumeros;         
           JOptionPane.showMessageDialog(null,"El valor total de la suma es: " + suma);
           JOptionPane.showMessageDialog(null, "El promedio es:" + promedio);        
    }    
}
    
answered by 12.07.2016 / 13:05
source