我正在运行这段代码,但是为什么m的输出结果总是为零呢?
这很奇怪,因为m被初始化为2。

public class ScalabilityTest {

public static void main(String[] args) {
    long oldTime = System.currentTimeMillis();
    double[] array = new double[100000];
    int p = 2;
    int m = 2;
    for ( int i = 0; i < array.length; i++ ) {
        p += p * 12348;
        for ( int j = 0; j < i; j++ ) {
            double x = array[j] + array[i];
            m += m * 12381923;
        }
    }

    System.out.println( (System.currentTimeMillis()-oldTime) / 1000 );
    System.out.println( p + ", " + m );
    }

}

最佳答案

由于您总是将m的值与一个数字相乘,并将其添加到m,因此在第16次迭代时,它会溢出而变为0
事实上,由于您将数字与奇数相乘,然后将其添加到原始数字中,您将数字与偶数相乘,这将使后面的0位至少向左移动一步,因此它以0结尾:

1 1011110011101110111001000 24763848
2 1111011100110010111011000100000 2073654816
3 1111111111111101111010010000000 2147415168
4 10010100011000001100001000000000 -1805598208
5 10010010100010001100100000000000 -1836529664
6 10001011110000100010000000000000 -1950212096
7 1110010101001001000000000000000 1923383296
8 1001100000100000000000000000 159514624
9 1010011110010000000000000000000 1405616128
10 10001110001000000000000000000000 -1910505472
11 1010100100000000000000000000000 1417674752
12 1000010000000000000000000000000 1107296256
13 11001000000000000000000000000000 -939524096
14 100000000000000000000000000000 536870912
15 10000000000000000000000000000000 -2147483648
16 0 0

关于java - 为什么此值的输出结果始终为零?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17095903/

10-09 00:37