测试double的值是否小于int的最大值

问题描述 投票:-1回答:2

假设ddouble变量。如果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变量?

java int double
2个回答
0
投票

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,与<=。)


1
投票

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.