为什么双 1.0 等于 int 1? [英] why a double 1.0 its equal to an int 1?

查看:43
本文介绍了为什么双 1.0 等于 int 1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我问为什么一个double加10乘0.10不等于int 1;

Yesterday I asked why a adding 10 times 0.10 to a double is not equal to int 1;

在 VB 中为什么 (1 = 1) 是 False

我得到了一个很好的答案.概述是因为:

I got an excellent answer. The overview is because:

  • 浮点类型和整数类型不能直接比较,因为它们的二进制表示不同.
  • 作为浮点类型的 0.1 相加十次的结果很可能是一个接近 1 的值,但不完全是

我现在可以看到原因了.但是,如果我执行以下操作:

I can see the reason why now. However, if I do something like:

  Dim d As Double

  For i = 1 To 4
        d = d + 0.25
  Next

  MsgBox(d)  'output 1 
  MsgBox(d = 1) 'True
  MsgBox(1 - d) ' 0
  Console.WriteLine(d) '1

在这种情况下,我确实获得了 double 1.0 和 int 1 之间的相等性.我当时认为 double 只是近似值,所以我希望 d 以某种方式接近 1 的值,就像最初的第一个问题一样.为什么直接比较不同的数据类型(在本例中为双整数)不是一个好主意,为什么我这次获得相等性??

In this case I really obtain equality between double 1.0 and int 1. I thought then that double were only approximations so I would expect d to be somehow a value close to 1 as in the original first question. Why is not a good idea to compare directly different data types (in this case double - integer) and why I this time I obtain equality ??

推荐答案

是的,双打通常是近似值.但有些数字比其他数字效果更好.

Yes, doubles are usually aproximations. But some numbers work better than others.

就像十进制数一样:您可以精确地写出 1/10 (0.1),但不能精确地写出 1/3 (0.33333...).

Just like decimal numbers: you can write 1/10 exactly (0.1), but not 1/3 (0.33333...).

所以碰巧 1/4 可以准确地转换为二进制浮点数,而 1/10 则不能.

So it happens that 1/4 can be converted exactly to a binary floating point number, where 1/10 can't be.

编辑
十进制(浮点)数字使用 10 的幂,因此如果您可以将某个数字写为 1/10、1/100、1/1000 等(允许倍数)的组合,那么您可以将该数字精确地写为小数号.

EDIT
A decimal (floating point) numbers works with powers of 10, so if you can write some number as a combination of 1/10, 1/100, 1/1000 etc (multiples allowed) then you can write that number exactly as a decimal number.

对于二进制浮点数,它的工作原理是一样的,只有序列是 1/2、1/4、1/8、1/16 等.另外,在计算机中,精度是有限制的:有些细节太过分了小到准确表示.

For binary floating point numbers it works the same, only the sequence is 1/2, 1/4, 1/8, 1/16 etc. Plus in computers there is a limit in the precision: some details are just too small to represent exactly.

这篇关于为什么双 1.0 等于 int 1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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