【问题标题】:Java power of number calculation problem with big numbers [duplicate]Java 大数的数字计算问题[重复]
【发布时间】:2020-10-25 09:31:35
【问题描述】:

我是 Java 新手,当我试图在没有 Math.pow 方法的情况下找到数字的幂时,我意识到答案不正确。我想知道为什么?

public class Main() {

int x = 1919;
int y = x*x*x*x;

public static void main(String[] args) {

System.out.println(y);
}
}

输出:2043765249

但通常答案是:13561255518721

【问题讨论】:

  • 提示:最大可能有多大int
  • 使用BIgInteger
  • @Joe:这个问题是关于浮点数以及pow 返回浮点数的事实。这里没有浮点数,也没有pow的用法。
  • 我不明白为什么有人会反对这个,即使这是一个绝对的初学者问题。作者确实提供了正确的代码和预期的结果。
  • 使用long 而不是int

标签: java calculation


【解决方案1】:

如果你一步一步走,你会看到值变成负数,那是因为你到达Integer.MAX_VALUE,也就是2^31 -1

int x = 1919;
int y = 1;
for (int i = 0; i < 4; i++) {
    y *= x;
    System.out.println(i + "> " + y);
}

0> 1919
1> 3682561
2> -1523100033
3> 2043765249

您可以使用更大的类型,例如 doubleBigInteger

double x = 1919;

double y = x * x * x * x;
System.out.println(y); // 1.3561255518721E13

BigInteger b = BigInteger.valueOf(1919).pow(4);
System.out.println(b); // 13561255518721

【讨论】:

    【解决方案2】:

    你使用一个 int 作为答案,你得到一个数字溢出。

    y 使用 double 或 long 或 BigInteger,您会得到正确的答案。

    public class Main {
    
        public static void main(String[] args) {
            System.out.println(Math.pow(1919, 4));
            System.out.println((double) 1919*1919*1919*1919);
        }
    }
    

    输出相同的值。

    【讨论】:

      【解决方案3】:

      使用long 而不是int

      public class Main{
          public static void main(String[] args) {
              long x = 1919;
              long y = x*x*x*x;
              System.out.println(y);
          }
      }
      

      Read about variables in Java.

      【讨论】:

        猜你喜欢
        • 2014-07-04
        • 2014-01-17
        • 2011-04-28
        • 1970-01-01
        • 2020-04-22
        • 2019-09-18
        • 2021-02-02
        • 2015-07-05
        • 1970-01-01
        相关资源
        最近更新 更多