我有这个问题:
您认为执行以下 Java 代码段后变量 result 的值是多少?
int i = 1234567890;
float f = i;
int result = i - (int)f;
答案非零
请记住,我是 Java 的初学者,目前正在学习绝对的基础知识,坦率地说,我不明白为什么答案是非零的,以及每行代码的实际含义是什么?
如果您想要小数的准确性,请使用BigDecimal
类而不是float
浮点类型。
float
/Float
和double
/使用的浮点技术以Double
牺牲准确性换取执行速度。切勿在准确性很重要的地方使用这些类型,例如金钱。
因此,将整数转换为浮点数并再次返回可能不会产生相同的数字。
此行为并非特定于 Java。Java 实现了定义浮点算术行为的电气工程标准。任何支持标准浮点的编程语言都会出现同样的问题。
int i = 1234567890; // Create an integer number from literal input, and store as a primitive value in variable named `i`.
float f = i ; // Convert the integer `int` primitive to a fractional number represented using floating-point technology as a primitive value in variable named `f`.
int backAgain = (int)f ; // Cast (convert) from a `float` type to a `int` type. Data-loss may be involved, as any fraction is truncated.
int result = i - backAgain ; // Subtract one `int` primitive from the other `int` primitive. Store the integer result in a primitive `int` variable.
boolean isZero = ( result == 0 ) ; // Test if the result of our subtraction is zero.
i: 1234567890
f: 1.23456794E9
backAgain: 1234567936
result: -46
isZero: false
BigDecimal
如果您在处理小数时想要准确性而不是速度,请使用BigDecimal
class。
int i = 1234567890;
BigDecimal bd = new BigDecimal( i ) ;
int backAgain = bd.intValueExact() ;
int result = i - backAgain ;
boolean isZero = ( result == 0 ) ;
isZero: true
i: 1234567890
bd: 1234567890
backAgain: 1234567890
result: 0
isZero: true
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句