我寫了一個程序,我不知道我應該如何做小數格式?我以爲我做得很對,顯然我不能正確地做十進制格式。可以,有人幫我用十進制格式?十進制格式問題Java
這裏是我的代碼:
import java.text.DecimalFormat;
import java.util.*;
public class Mean {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
double[]x = new double[10];
int i;
for(i = 0;i < 10; i++){
x[i] = s.nextDouble();
}
double mean = mean(x, i);
double deviation = var(x);
System.out.println("The mean is " + mean);
System.out.println("The standard deviation is " + deviation);
}
public static double sum(double[] a) {
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
public static double mean(double[]x, double i){
if (x.length == 0) return Double.NaN;
double sum = sum(x);
return sum/x.length;
}
public static double var(double[] x) {
if (x.length == 0) return Double.NaN;
double avg = mean(x, 10);
double sum = 0.0;
for (int i = 0; i < x.length; i++) {
sum += (x[i] - avg) * (x[i] - avg);
}
DecimalFormat myFormatter = new DecimalFormat("#,##0.00");
return sum/myFormatter.format(Math.sqrt(x.length - 1));
}
}
它取決於你希望你的小數點格式是怎麼樣的? –
顯示你想要的輸出,電流輸出和輸入 –
(我想要的)有點這樣:1,234.56(在第二個十進制數之後舍入)。 (我得到)錯誤! – Wumbo