木人白住 2021-04-20 09:53 采纳率: 100%
浏览 61
已采纳

Java为什么BigInteger的数据存到数组里翻倍了

今天我做到一题:

(被5或6整除)找出能被5或6整除的前10个数字(大于Long.MAX_VALUE)

正确的答案是这样的

import java.math.BigInteger;

public class Exercise10_21 {
    public static void main(String[] args) {
        BigInteger m = BigInteger.valueOf(Long.MAX_VALUE);
        int j = 0;
        for(int i = 1; j<10 ; i++) {
            BigInteger x = m.add(BigInteger.valueOf(i));
            if((x.mod(BigInteger.valueOf(5)).equals(BigInteger.valueOf(0)) || x.mod(BigInteger.valueOf(6)).equals(BigInteger.valueOf(0)))) {
                System.out.println(x);
                j++;
            }
        }
    }
}
9223372036854775810
9223372036854775812
9223372036854775815
9223372036854775818
9223372036854775820
9223372036854775824
9223372036854775825
9223372036854775830
9223372036854775835
9223372036854775836

但是一旦我先存入数组在输出答案

import java.math.BigInteger;

public class Exercise10_21 {
    public static void main(String[] args) {
        BigInteger m = BigInteger.valueOf(Long.MAX_VALUE);
        BigInteger a[]= new BigInteger[10];
        int j = 0;
        for(int i = 1; j<10 ; i++) {
            BigInteger x = m.add(BigInteger.valueOf(i));
            if((x.mod(BigInteger.valueOf(5)).equals(BigInteger.valueOf(0)) || x.mod(BigInteger.valueOf(6)).equals(BigInteger.valueOf(0)))) {
                a[j] = m.add(x);
                System.out.println(a[j]);
                j++;
            }
        }
    }
}
18446744073709551617
18446744073709551619
18446744073709551622
18446744073709551625
18446744073709551627
18446744073709551631
18446744073709551632
18446744073709551637
18446744073709551642
18446744073709551643

输出的结果就翻倍了,请问这是为什么,以及解决办法。

  • 写回答

4条回答 默认 最新

  • 张小帅和刘美美 2021-04-20 10:01
    关注

    你自己代码的问题 add两次

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?