float数据类型是单精度32位IEEE 754浮点,double数据类型是双精度64位IEEE 754浮点。
什么意思?什么时候我应该使用float而不是double,反之亦然?
发布于 2014-12-22 15:16:28
一个浮点数给你一个近似的。6-7个十进制数字的精度,而双精度则给出大约。15-16。同样,double的数字范围也更大。
double需要8字节的存储空间,而float只需要4字节。
发布于 2016-02-21 23:45:23
尽管如此,Java似乎偏向于使用double进行计算:
例如,我今天早些时候写的程序,当我使用float时,这些方法不起作用,但现在当我用double替换float时,效果很好(在NetBeans集成开发环境中):
package palettedos;
import java.util.*;
class Palettedos{
private static Scanner Z = new Scanner(System.in);
public static final double pi = 3.142;
public static void main(String[]args){
Palettedos A = new Palettedos();
System.out.println("Enter the base and height of the triangle respectively");
int base = Z.nextInt();
int height = Z.nextInt();
System.out.println("Enter the radius of the circle");
int radius = Z.nextInt();
System.out.println("Enter the length of the square");
long length = Z.nextInt();
double tArea = A.calculateArea(base, height);
double cArea = A.calculateArea(radius);
long sqArea = A.calculateArea(length);
System.out.println("The area of the triangle is\t" + tArea);
System.out.println("The area of the circle is\t" + cArea);
System.out.println("The area of the square is\t" + sqArea);
}
double calculateArea(int base, int height){
double triArea = 0.5*base*height;
return triArea;
}
double calculateArea(int radius){
double circArea = pi*radius*radius;
return circArea;
}
long calculateArea(long length){
long squaArea = length*length;
return squaArea;
}
}
发布于 2015-06-15 07:25:29
根据IEEE标准,float是实数的32位表示,而double是64位表示。
在Java程序中,我们通常主要看到双精度数据类型的使用。这只是为了避免溢出,因为使用double数据类型可以容纳的数字范围比使用float时的范围要大。
此外,当需要高精度时,鼓励使用double。很少有很久以前实现的库方法仍然需要使用float数据类型(这只是因为它是使用float实现的,没有其他的!)。
但是,如果您确定您的程序需要较小的数字,并且使用float不会发生溢出,那么使用float将极大地提高您的空间复杂性,因为float需要的内存是double所需的一半。
https://stackoverflow.com/questions/27598078
复制相似问题