为什么4.1%2使用Ruby返回0.0999999999999996?但是4.2%2 == 0.2 [英] Why 4.1%2 returns 0.0999999999999996 using Ruby?But 4.2%2==0.2

查看:69
本文介绍了为什么4.1%2使用Ruby返回0.0999999999999996?但是4.2%2 == 0.2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么4.1%2返回0.0999999999999996?但是4.2%2 == 0.2.

Why 4.1%2 returns 0.0999999999999996?But 4.2%2==0.2.

推荐答案

请参见此处:每个程序员应了解的浮点算法

实数是无限的.计算机正在使用有限数量的位(32位,今天为64位).结果,计算机执行的浮点运算不能代表所有实数. 0.1是这些数字之一.

Real numbers are infinite. Computers are working with a finite number of bits (32 bits, 64 bits today). As a result floating-point arithmetic done by computers cannot represent all the real numbers. 0.1 is one of these numbers.

请注意,这不是与Ruby有关的问题,而是与所有编程语言有关的问题,因为它来自计算机表示实数的方式.

Note that is not an issue related to Ruby, but to all programming languages because it comes from the way computers represent real numbers.

这篇关于为什么4.1%2使用Ruby返回0.0999999999999996?但是4.2%2 == 0.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆