首页 > 解决方案 > 在java中使用命令行参数时没有得到正确的输出

问题描述

//Square root of a no. using command line argument
class Calculator {
    double i;
    double x = Math.sqrt(i);
}

class SquareRoot {
    public static void main(String arg[]) {
        Calculator a = new Calculator();
        a.i = Integer.parseInt(arg[0]);
        System.out.println("The square root of " + a.i + " is " + a.x);
    }
}

我的输出:

The square root of 64 is 0.0

我的代码有什么问题?

标签: javamath.sqrt

解决方案


尝试这个 :

class Calculator {
    double i, x;
    void squareRoot() {
        x = Math.sqrt(i);
    }
}

class SquareRoot {
    public static void main(String arg[]) {
        Calculator a = new Calculator();
        a.i = Integer.parseInt(arg[0]);
        a.squareRoot();
        System.out.println("The square root of " + a.i + " is " + a.x);
    }
}

推荐阅读