我有一个问题:
在执行以下Java代码段之后,您认为变量结果的值是什么?
int i = 1234567890;
float f = i;
int result = i - (int)f;答案是非零
请记住,我是java的初学者,目前我正在学习绝对基础知识,坦率地说,我不明白为什么答案是非零,以及代码的每一行实际上意味着什么?
发布于 2021-07-16 20:47:47
tl;dr
如果您想要分数数字的准确性,请使用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: falseBigDecimal
如果您在处理小数时想要的是准确性而不是速度,请使用BigDecimal类。
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: truehttps://stackoverflow.com/questions/68414942
复制相似问题