Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
当我在 irb 控制台中添加两个浮点数时,结果与预期不符
10.43 + 4.56 # should be 14.99
但实际结果是
irb(main):001:0> 10.43+4.56 => 14.989999999999998
这是什么原因造成的?
这是预期的行为。浮点数不能保证精度,因为简而言之,计算机是二进制系统(截至 2013 年),不能正确表示小数值。这就是为什么您会得到“意外”结果的原因,而实际上这就是它的工作方式,直到有一台可以正确表示小数值的非二进制机器。