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));
}
}
输出:
Enter the quantity of numbers for averaging : 2
Enter the number for averaging : 3
Enter the number for averaging : 4
Average =3.00
答案 0 :(得分:-1)
您必须执行以下操作:
double ave = (double) temp / n;
否则temp / n
是一个整数表达式,首先使用整数数学求值,然后 then 转换为双精度。您必须将其中一个操作数先转换为双精度,然后才能进行除以双精度除法运算。