在 VB 为什么 (1 = 1) 是 False [英] in VB Why (1 = 1) is False

查看:51
本文介绍了在 VB 为什么 (1 = 1) 是 False的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚遇到了这段代码:

I just came across this piece of code:

Dim d As Double

For i = 1 To 10
  d = d + 0.1
Next

MsgBox(d)
MsgBox(d = 1)
MsgBox(1 - d)

谁能解释一下原因?为什么 d 设置为 1?

Can anyone explain me the reason for that? Why d is set to 1?

推荐答案

浮点类型和整数类型不能直接比较,因为它们的二进制表示不同.

Floating point types and integer types cannot be compared directly, as their binary representations are different.

0.1 作为浮点类型相加十次的结果很可能是一个接近到 1 的值,但不完全是.

The result of adding 0.1 ten times as a floating point type may well be a value that is close to 1, but not exactly.

在比较浮点值时,您需要使用一个最小值,通过该最小值,这些值可以不同但仍被视为相同的值(该值通常称为 epsilon).此值取决于应用程序.

When comparing floating point values, you need to use a minimum value by which the values can differ and still be considered the same value (this value is normally known as the epsilon). This value depends on the application.

我建议阅读每个计算机科学家都应该了解的关于浮点运算的内容 进行深入讨论.

I suggest reading What Every Computer Scientist Should Know About Floating-Point Arithmetic for an in-depth discussion.

至于将 1 转换为 1.0 - 它们是不同的类型,因此不会相互比较.

As for comaring 1 to 1.0 - these are different types so will not compare to each other.

这篇关于在 VB 为什么 (1 = 1) 是 False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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