【问题标题】:Java keeps returning incorrect answer [duplicate]Java不断返回不正确的答案[重复]
【发布时间】:2015-02-22 18:26:16
【问题描述】:

a 是微调器的值。

private void toolCalculateActionPerformed(java.awt.event.ActionEvent evt) {
    Integer a = (int) toolSpinner.getValue();

    if (toolEnch.getSelectedIndex() == 0) {
        double p;
        p = (10 ^ (2 - a) * 13 ^ a);
        double x = Math.round(p);
        System.out.println(x);
    }
}

我在做10^(2-a) * 13^a,并且

假设微调器在 1,它返回 6,它应该返回 130。

假设微调器在 2,它返回 8,它应该返回 169。

我已经用 WolframAlpha 对其进行了测试,它给了我正确的结果。然而,这个程序给了我一些东西。 有关如何解决此问题的任何想法?

【问题讨论】:

    标签: java


    【解决方案1】:

    ^ 是 XOR,而不是指数。如果你想要指数,请使用Math.pow

    p = Math.pow(10, (2-a)) * Math.pow(13, a);
    

    【讨论】:

    • 啊,好的!我以为 ^ 是指数。谢谢!
    【解决方案2】:

    您的操作写错了优先级,^ 是 XOR 而不是 POW,实际上您必须使用括号自己处理优先级。因为括号比每个操作具有更高的优先级。 使用数学课 像这样更改 p 变量行:

    p = Math.pow(10, (2-a)) * Math.pow(13, a); // it will be 130.0 in double format when a is 1
    

    如果你想计算其他任何东西,比如 XOR 大多数时候你必须自己处理优先级! 像这样:

     int a = 1;
     double p = 0;
     p = ((10 + (2-a)) * (13 + a));
     System.out.println(p);; // this will be 154.0 in double format.
    

    但是这个:

     int a = 1;
     double p = 0;
     p = (10 + (2-a) * (13 + a));
     System.out.println(p); // will print 24.0 in double format.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 2015-05-18
      • 1970-01-01
      • 2015-06-30
      • 1970-01-01
      相关资源
      最近更新 更多