Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java打印出一个双数组_Java - Fatal编程技术网

java打印出一个双数组

java打印出一个双数组,java,Java,我有一个数组,里面有一些双值: private double speed[] = {50, 80, 120, 70.3}; public void printSpeed() { for(int i = 0; i<=speed.length-1; i++ ) { System.out.println(speed[i]); } } output 50.0 80.0 12.0 70.3 wanted output 50 80 12 70.3 privat

我有一个数组,里面有一些双值:

private double speed[] = {50, 80, 120, 70.3};

public void printSpeed() {
    for(int i = 0; i<=speed.length-1; i++ ) {
        System.out.println(speed[i]);
    }
}

output 
50.0
80.0
12.0
70.3

wanted output
50
80
12
70.3
private double speed[]={50,80,120,70.3};
公共空间打印速度(){

对于(int i=0;i<P)>首先要注意的是:最终值将不完全是70.3,因为在双< /代码>中不能精确表示。如果精确的十进制值对您很重要,则应考虑使用<代码> BigDecimal < /C> >。< /P> 听起来您需要一个
NumberFormat
,它省略了后面不重要的数字:

import java.text.*;

public class Test {

    public static void main(String[] args) {
        // Consider specifying the locale here too
        NumberFormat nf = new DecimalFormat("0.#");

        double[] speeds = { 50, 80, 120, 70.3 };
        for (double speed : speeds) {
            System.out.println(nf.format(speed));
        }
    }

}
(顺便说一句,我强烈建议您为具有类型信息的数组声明保留
[]
double[]speed
,而不是
double[]
。它是更惯用的Java,它将所有类型信息放在一个位置。)

尝试以下方法:

 System.out.println(String.format("%.0f", speed[i]));
请尝试:

for(int i = 0; i < speed.length; i++ ) {
    long l = (long)speed[i];
    if(l == speed[i]) {
        System.out.println(l);
    } else {
        System.out.println(speed[i]);
    }
}
for(int i=0;i
System.out.println(速度[i]).toString().replace(“.0”,”)?