gpt4 book ai didi

java - Java十进制格式问题

转载 作者:行者123 更新时间:2023-11-30 04:05:56 25 4
gpt4 key购买 nike

我写了一个程序,但我不知道应该如何处理十进制格式?我认为我做得对,显然我不能正确地处理十进制格式。有人可以帮我处理十进制格式吗?

这是我的代码:

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));

}
}

最佳答案

尝试这个来格式化你的 double ...我还必须更新你的方法var -

public static String formatDouble(double in) {
DecimalFormat myFormatter = new DecimalFormat(
"#,##0.00");
return myFormatter.format(in);
}

public static double var(double[] x) {
if (x.length == 0)
return Double.NaN;
double avg = mean(x);
double sum = 0.0;
for (int i = 0; i < x.length; i++) {
sum += (x[i] - avg) * (x[i] - avg);
}
return sum / Math.sqrt(x.length - 1);
}

public static void main(String[] args) {
double[] x = new double[] {
2000.20, 1000.10, 3000.30, 4000.40,5000.50,
6000.60,7000,70,8000.80,9000.90
};
double mean = mean(x);
double deviation = var(x);
System.out.println("The mean is "
+ formatDouble(mean));
System.out.println("The standard deviation is "
+ formatDouble(deviation));
}

关于java - Java十进制格式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20726531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com