假设d
是double
变量。如果int
中的值不大于i
的最大值,则写一个if语句,将d分配给d
变量int
。
下面的方法是我尝试这个问题:
public static void assignInt(double d)
{
int i = 0;
if(d < Integer.MAX_VALUE)
i = (int)d;
System.out.print(i);
}
Integer.MAX_VALUE
持有2147483647
。我假设这是int
可以容纳的最大值?考虑到这个假设,我试图三次打电话给assingDoubleToInt()
:
public static void main(String[] args)
{
assignDoubleToInt(2147483646); //One less than the maximum value an int can hold
assignDoubleToInt(2147483647); //The maximum value an int can hold
assignDoubleToInt(2147483648);//One greater than the maximum value an int can hold. Causes error and does not run.
}
前两个调用输出:
2147483646
0
而第三个电话,assignDoubleToInt(2147483648);
,投掷"The literal 2147483648 of type int is out of range."
这不是比较2147483648 < 2147483647
?如果比较应该评估为i
,为什么false
被赋值?
使用比较d < Integer.MAX_VALUE
不是正确的方法。如何测试double
变量是否适合int
变量?
Integer.MAX_VALUE
持有2147483647
。我假设这是int可以容纳的最大值?
是。
投掷
"The literal 2147483648 of type int is out of range."
你不能创建一个代表int
范围之外的数字的int
文字,所以2147483647
是合法的,但2147483648
不是。如果你想要一个更大的整数文字,使用一个长文字,附加字母L:2147483648L
,或带小数点的双字面(或附加D):2147483648.0
(或2147483648D
)。
这不是正确的方法。
比较d < Integer.MAX_VALUE
是合法的
并纠正
,因为Integer.MAX_VALUE
将扩大到double
进行比较,而double
的价值可能比Integer.MAX_VALUE
大得多。您只需要确保您可以传递正确的值,如上所述。
(如上面的评论所述,它应该是d <= Integer.MAX_VALUE
,与<=
。)
int范围问题是因为你有一个int文字。通过后缀“d”使用双字面值:
public static void main(String[] args) {
assignDoubleToInt(2147483646); // One less than the maximum value an int can hold
assignDoubleToInt(2147483647); // The maximum value an int can hold
assignDoubleToInt(2147483648d);// One greater than the maximum value an int can hold. Causes error and does not
// run.
}
我相信你的相等测试应该是<=
,也是:“如果d中的值不大于int的最大值” - 所以如果它与int的最大值相等,则它是有效的:
public static void assignDoubleToInt(double d) {
int i = 0;
if (d <= Integer.MAX_VALUE)
i = (int) d;
System.out.println(i);
}