我有点困惑。一旦我16岁及以上,随机选择x是0.为什么?
Random random = new Random();
for(int i = 1; i < 20; i++)
{
int[] input = generateArray( (int)Math.round(Math.pow(2, i)), (int)Math.round(Math.pow(2, i+i)) );
int x = input[random.nextInt(input.length-1)];
System.out.println(BinarySearch.go(input, x));
}
抱歉,我忘了向你展示generateArray:
public static int[] generateArray(int amount, int max)
{
int[] randomNumbers = new int[amount];
double delta = max / (float)amount;
Random random = new Random();
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = (int)Math.round(i*delta + random.nextDouble() * delta);
}
return randomNumbers;
}
基本上生成一个长度为量的int数组,并随机填充(bound = amount * 2),发现增加整数。
答案 0 :(得分:1)
generateArray
的第二个参数比第一个i+i
指数级增长得快。在16位,实际上2 31 - 1溢出int,
public static void main(String[] args) {
for (int i = 15; i < 20; i++) {
long a = Math.round(Math.pow(2, i));
long b = Math.round(Math.pow(2, i + i));
int c = (int) b;
System.out.printf("i = %d, a = %d, b = %d, c = %d%n", i, a, b, c);
}
}
输出
i = 15, a = 32768, b = 1073741824, c = 1073741824
i = 16, a = 65536, b = 4294967296, c = 0
i = 17, a = 131072, b = 17179869184, c = 0
i = 18, a = 262144, b = 68719476736, c = 0
i = 19, a = 524288, b = 274877906944, c = 0
答案 1 :(得分:1)
考虑
Math.round(Math.pow(2, i + i))
其中i = 16
(如果i
大于16,则类似的结果)。
那是2^32
,以二进制形式表示为
<leading 0s>1 00000000 00000000 00000000 00000000
这是long
,它不适合int
。您执行转换,丢弃前导位,并获得int
0
的值。