为什么浮点数除以更大的浮点数会得到零,在 C# 中如何避免这种情况?
我试图除 (float)200 / (float)500
但结果是 0.0。为什么会这样?我们怎么能得到 0.4 的结果呢?多谢。
I was trying to divide (float)200 / (float)500
but the result is 0.0. Why is this so and how can we have 0.4 as the result? Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个非常常见的错误,每个程序员都至少犯过一次。有两种除法运算符,它们都使用相同的符号:整数和浮点。编译器根据操作数的类型选择使用哪个。如果左操作数和右操作数都是整数,那么您将得到整数除法。机器代码中的 idiv 指令。它截断为零并产生整数结果。
一旦至少一个操作数是浮点,您就会得到机器代码中的 fdiv 指令以及您正在寻找的结果。只需转换为 (float) 或 (double) 就足够了,就像您在问题中所做的那样。您只需施放其中之一即可。或者使用浮点文字,例如 200f 或 200.0
It is a very common mistake, every programmer makes it at least once. There are two kind of division operators, they both use the same symbol, integral and floating point. The compiler chooses which it uses based on the types of the operands. If both the left- and right-hand operands are integral then you'll get an integral division. The idiv instruction in machine code. Which truncates to zero and produces an integral result.
As soon as at least one operand is floating point, you'll get the fdiv instruction in machine code and the result you are looking for. Simply casting to (float) or (double) is enough, like you did in your question. You only have to cast one of them. Or use a floating point literal like 200f or 200.0
那是不可能的。我可以想到以下场景:
That's impossible. I can think of the following scenarios:
这里没什么问题——我和安德烈亚斯在一起。
结果:
Nothing wrong here - I'm with Andreas.
Results in:
我在使用 Unity3D 项目的 MonoDevelop 调试器中遇到了这个问题。不知何故,评估窗口显示 1.0f/10.0f = 0 长。这只是 MonoDevelop IDE 的一个错误。
I experienced this problem in MonoDevelop debugger with Unity3D project. Somehow Evaluate window shows 1.0f/10.0f = 0 long. This is just a bug of MonoDevelop IDE.