十进制格式问题Java [英] Decimal Format Issues Java

查看:88
本文介绍了十进制格式问题Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一段代码,我无法将其格式化(十进制)。



这是我的代码:

折叠|复制代码

I wrote a snippet of code and i can't get it to be formatted (decimal).

Here is my code:
Collapse | Copy Code

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值进行格式化,而不是在被调用方法中。看到下面的更改,我假设你想要两个小数位的双倍,如果不是你总是可以问google。



Your formula for standard deviation seems odd, you may want to check with google. However, that is not issue here.
You should only do the formatting on the return double value in the calling method not in the called method. See the changes below, I am assuming you want double with 2 decimal places, if not you can always ask google.

public static void main(String [] args){
             
          // your other code
          double deviation = var(x);
          DecimalFormat df = new DecimalFormat("#.##");
          System.out.println("The standard deviation is " + df.format(deviation));
    }

    public static double var(double[] x) {
        // your other code
        double deviation = Math.sqrt(sum/(x.length - 1));
        return deviation;
        //DecimalFormat myFormatter = new DecimalFormat("#,##0.00");
        //return sum / myFormatter.format((Math.sqrt(x.length - 1)));
    }


好朋友,我已经把它想出来了......; D
it's alright buddy, i already figured it out... ;D


这篇关于十进制格式问题Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆