【问题标题】:diffrence between "<" less than operator and "<=" operator when comparing large numbers using pow(x,y)使用 pow(x,y) 比较大数时“<”小于运算符和“<=”运算符之间的区别
【发布时间】:2015-07-23 08:23:46
【问题描述】:

当我尝试将数字 9223372036854775807 与 Math.pow(2,63) 进行比较时,它给出了错误的答案。这是代码

long s = (long) (Math.pow(2, 63) - 1) ;
if ((s < Math.pow(2, 63)) && (s >= -Math.pow(2, 63)))
            System.out.println("* long");

这不会打印任何东西,而当我这样做时它会打印

long s = (long) (Math.pow(2, 63) - 1) ;
if ((s <= Math.pow(2, 63)) && (s >= -Math.pow(2, 63)))
            System.out.println("* long");

实际的程序是这样的......

package practice;

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Ques2ofHR_database {

public static void main(String[] args) {

    int i;
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    for (i = 0; i < n; i++) {

        long s =0;
    try {
            s = in.nextLong();

        } catch (InputMismatchException e) {
            System.out.println(in.next() + " can't be fitted anywhere.");

            continue;
        }


    System.out.println(s + " can be fitted in:");
        if ((s < Math.pow(2, 7)) && (s >= -Math.pow(2, 7)))
            System.out.println("* byte");

        if ((s < Math.pow(2, 15)) && (s >= -Math.pow(2, 15)))
            System.out.println("* short");

        if ((s < Math.pow(2, 31)) && (s >= -Math.pow(2, 31)))
            System.out.println("* int");

        if ((s <= Math.pow(2, 63)) && (s >= -Math.pow(2, 63)))
            System.out.println("* long");

    }

    }

}

这个程序实际上找出了所有可以存储给定数字的数据类型(字节、短、整数和长)

提前谢谢...

【问题讨论】:

  • 精度损失after 52 bits: Math.pow(2, 63) - 1 == Math.pow(2, 63) 是真的

标签: java types operators


【解决方案1】:

Long.MAX_VALUE 需要 64 位才能放入长变量中。

Math.pow(2,63) 返回一个双精度值。 double 使用相同数量的位 (64) 来近似更大的浮点数(一些位被指数使用),所以 Math.pow(2,63) 不能等于 Long.MAX_VALUE,因为 Long.MAX_VALUE 可以t 可以用双精度变量准确表示。

编辑:

实际上,Math.pow(2, 63) 可以用双精度变量准确表示,因为它是 2 的幂,指数相对较小。但是,当您从中减去 1 时,您会得到一个无法在 double 变量中准确表示的数字。

【讨论】:

  • 但是当我用 "
  • @user4885727 当您将 long 与 double 进行比较时,long 将转换为 double。在您的情况下,由于 9223372036854775807 不能准确地表示为双精度,它被转换为最接近的双精度值,显然等于 Math.pow(2, 63)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-24
  • 1970-01-01
  • 2015-07-03
  • 1970-01-01
  • 1970-01-01
  • 2015-12-09
相关资源
最近更新 更多