当我尝试将数字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");
}
}
}这个程序实际上找出了所有可以存储给定数字的数据类型(在byte、short、int和long之间)
先谢谢你……
发布于 2015-07-23 16:31:18
Long.MAX_VALUE需要64位才能放入长变量中。
Math.pow(2,63)返回一个双精度值。double使用相同的位数(64)来近似更大的浮点数(其中一些位由指数使用),因此Math.pow(2,63)不能等于Long.MAX_VALUE,因为Long.MAX_VALUE不能用double变量精确表示。
编辑:
实际上,Math.pow(2, 63)可以用双变量精确表示,因为它是2的幂,指数相对较小。然而,当你从它中减去1,你得到一个不能在双变量中准确表示的数字。
https://stackoverflow.com/questions/31581920
复制相似问题