-1
import java.util.Scanner;
import java.text.DecimalFormat; 

public class average_of_N 
{
    public void format(double d)
    {
        System.out.println(d);
    }
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in); 
        DecimalFormat df = new DecimalFormat("0.00"); 

        System.out.print("Enter the quantity of numbers for averaging : "); 
        int n = sc.nextInt(); 
        int temp = 0;

        for(int i=0;i<n;i++)
        {
            System.out.print("Enter the number for averaging : ");
            int x = sc.nextInt(); 
            int sum = temp + x; 
            temp = sum; 
        }

        double ave = temp / n; 

        System.out.println("Average =" + df.format(ave));
    }

}

Output :

Enter the quantity of numbers for averaging : 2
Enter the number for averaging : 3
Enter the number for averaging : 4
Average =3.00
ggorlen
  • 26,337
  • 5
  • 34
  • 50

1 Answers1

-1

You have to do something like:

double ave = (double) temp / n;

Otherwise temp / n is an integer expression, first evaluated using integer math and then cast to a double. You have to cast one of the operands to double first to get the division to be carried out as double precision division.

ggorlen
  • 26,337
  • 5
  • 34
  • 50
kshetline
  • 8,496
  • 4
  • 19
  • 44