【发布时间】: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)是真的