当将long转换为double和back时的值更改 [英] Value change when converting a long to a double and back

查看:82
本文介绍了当将long转换为double和back时的值更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

long l = 1234567890123;
double d = (double) l;

以下表达式是否为真?

l == (long) d



认为没有,因为随着数字变大,两个双精度之间的差距增长超过1,因此转换回来产生不同的长值。

I should think no, because as numbers get larger, the gaps between two doubles grow beyond 1 and therefore the conversion back yields a different long value. In case the conversion does not take the value that's greater than the long value, this might also happen earlier.

有没有确定的答案?

推荐答案

不,绝对不是。有大量的值不能由 double 完全表示。事实上,是这种情况,假定两种类型都用64位表示,并且显然有很多 double 值在 long (例如0.5)

Nope, absolutely not. There are plenty of long values which aren't exactly representable by double. In fact, that has to be the case, given that both types are represented in 64 bits, and there are obviously plenty of double values which aren't representable in long (e.g. 0.5)

代表的简单示例(Java,然后C#):

Simple example (Java and then C#):

// Java
class Test {
    public static void main(String[] args) {
        long x = Long.MAX_VALUE - 1;
        double d = x;
        long y = (long) d;
        System.out.println(x == y);
    }
}

// C#
using System;

class Test
{
    static void Main()
    {
        long x = long.MaxValue;
        double d = x;
        long y = (long) d;
        Console.WriteLine(x == y);
    }
}

>当这样做虽然...在C#中, long.MaxValue 工作的打印方面False ...而在Java中,我不得不使用 Long.MAX_VALUE - 1 。我的猜测是,这是由于一些内联和80位浮点运算在某些情况下...但它仍然奇怪:)

I observed something really strange when doing this though... in C#, long.MaxValue "worked" in terms of printing False... whereas in Java, I had to use Long.MAX_VALUE - 1. My guess is that this is due to some inlining and 80-bit floating point operations in some cases... but it's still odd :)

这篇关于当将long转换为double和back时的值更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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