(int)Math.pow(2,x)和1<< x的Java结果不同 [英] Java results differ for (int)Math.pow(2,x) and 1<<x

查看:305
本文介绍了(int)Math.pow(2,x)和1<< x的Java结果不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下两个操作在Java中为 x = 31 32 产生不同的结果,但结果相同对于 x = 3

Why do the following two operations yield different results in Java for x = 31 or 32 but the same results for x=3?

int x=3;
int b = (int) Math.pow(2,x);
int c = 1<<x;

结果:

x=32: b=2147483647; c=1;
x=31: b=2147483647; c=-2147483648;
x=3:  b=8         ; c=8


推荐答案

有多个问题在起作用:


  • int 只能存储 -2147483648之间的值 2147483647

  • 1<< x 使用 x 的最低五位。因此, 1<<根据定义,32 1<< 0

  • 移位操作在左操作数值的二进制补码整数表示;这解释了为什么 1<< 31 是否定的。

  • Math.pow(2,32)返回 double

  • (int)(d),其中 d double 大于 2147483647 返回 2147483647 最大的类型 int )的可表示值。

  • An int can only store values between -2147483648 and 2147483647.
  • 1 << x only uses the lowest five bits of x. Thus, 1 << 32 is by definition the same as 1 << 0.
  • Shift operations are performed on the two's-complement integer representation of the value of the left operand; this explains why 1 << 31 is negative.
  • Math.pow(2, 32) returns a double.
  • (int)(d), where d is a double greater than 2147483647 returns 2147483647 ("the largest representable value of type int").

这是什么面试问题确实显示(int)Math.pow(2,x) 1<< x 0 之外的 x 的值不等效... 30 范围。

What this interview question does is show that (int)Math.pow(2, x) and 1 << x are not equivalent for values of x outside the 0...30 range.

PS或许有趣的是,使用 long 代替 int (以及 1L 代替 1 )会给出另一组与其他两个不同的结果。即使最终结果转换为 int ,这也成立。

P.S. It is perhaps interesting to note that using long in place of int (and 1L in place of 1) would give yet another set of results different from the other two. This holds even if the final results are converted to int.

这篇关于(int)Math.pow(2,x)和1&lt;&lt; x的Java结果不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆