【问题标题】:Not getting correct output when using command line argument in java在java中使用命令行参数时没有得到正确的输出
【发布时间】:2020-02-01 05:07:44
【问题描述】:
//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

我的代码有什么问题?

【问题讨论】:

  • 因为double x=Math.sqrt(i);是在a.i=Integer.parseInt(arg[0]);之前计算出来的(而且是0)。
  • 所以要纠正它,我需要先创建一个方法,然后调用它。对吗?

标签: java math.sqrt


【解决方案1】:

试试这个:

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

【讨论】:

  • 所以不使用 squareRoot() 方法我不能直接做吗?你能进一步解释一下吗?
  • 在你的代码Math.sqrt(i) 在获取变量a的值之前执行。当您创建 calculator 类的对象时设置您的 x 值。这是在获取a的值之前执行的。这就是为什么你需要在获取i的值之后调用平方根函数。
猜你喜欢
  • 2015-10-28
  • 1970-01-01
  • 2011-06-30
  • 2017-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多