为什么(双)0.6f> (双)(6 / 10F)? [英] Why is (double)0.6f > (double)(6/10f)?

查看:105
本文介绍了为什么(双)0.6f> (双)(6 / 10F)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的电脑上会发生什么:

This is what happens on my computer:

(double)(float)0.6
= 0.60000002384185791

(double)0.6f
= 0.60000002384185791

(double)(6/10f)
= 0.6

(double)(float)(6/10f)
= 0.6

6 / 10F也是一个浮点数,怎么来的也可以是precisely 0.6?

在我的脑海里(双)(6 / 10F)也应该是0.60000002384185791。
有人可以帮助解释一下吗?谢谢!

6/10f is also a float,how come it can be precisely 0.6?
In my mind (double)(6/10f) should also be 0.60000002384185791. Can someone help explain this? thanks!

推荐答案

首先,它的重要的是要记住, 0.6 无法准确重新presented作为浮动然而,它的可以的精确重新psented为双击(不准确$ p $的浮点运算是有据可查的,如果不清楚为什么 0.6 无法准确重新psented为float $ p $,尝试的此链接

First, its important to bear in mind that 0.6 cannot be accurately represented as a float however it can be accurately represented as a double (the inaccuracies of floating point arithmetic are well documented, if its not clear why 0.6 cannot be accurately represented as a float, try this link)

为什么你看到上述行为的原因是下降到编译器 - 如果你看看在反射器编译的程序集,然后什么怎么回事是更清晰一点:

The reason why you are seeing the above behaviour is down to the compiler - if you take a look at the compiled assembly in reflector then whats going on here is a little clearer:

更新我已经改变了code,以便它不使用 Console.WriteLine ,因为我意识到了编译器选择你的过载,这搞不清楚状况)

(UPDATE I've changed the code so that it doesn't use Console.WriteLine, as I realised that the compiler was choosing an overload for you, which confused the situation)

// As written in source
var j = (double)(float)0.6;
var k = (double)0.6f;
var l = (double)(6/10f);
var m = (double)(float)(6/10f);

// Code as seen by Reflector
double j = 0.60000002384185791;
double k = 0.60000002384185791;
double l = 0.6;
double m = 0.6;

为什么编译器选择在这个特殊的方式编译超越我(仅供参考,这是所有的优化关闭)

Why the compiler chooses to compile in this particular way is beyond me (fyi, this is all with optimisations turned off)

一些有趣的其他情况:

// Code
var a = 0.6;
var b = (double)0.6;
var c = 0.6f;
var d = (float)0.6;

var e = 6 / 10;
var f = 6 / (10f);
var g = (float)(6 / 10);
var h = 6 / 10f;
var i = (double)6 / 10;
// Prints out 0.60000002384185791

double n = (float)0.6;
double o = f;

// As seen by Reflector
double a = 0.6;
double b = 0.6;
float c = 0.6f;
float d = 0.6f;

int e = 0;
float f = 0.6f;
float g = 0f;
float h = 0.6f;
double i = 0.6;

double n = 0.60000002384185791;
double o = f;

编译器似乎只能做上述伎俩在几个特殊情况下,为什么铸造到双当它这只是完全超出了我!

The compiler only seems to do the above trick in a couple of special cases, why it does this only when casting to a double is completely beyond me!

的其余时间似乎做一些挂羊头卖狗肉,以浮点运算的看起来的工作在哪里,其实它通常不会。

The rest of the time it seems to do some trickery to make floating point arithmetic seem to work where in fact it normally wouldn't.

这篇关于为什么(双)0.6f> (双)(6 / 10F)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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