【发布时间】:2011-06-21 23:27:34
【问题描述】:
我正在尝试将双精度转换为帕斯卡实数,但是当我将 0.23 转换为实数时,我得到了 0.23999999 实数,如何将所有 9999 截断为 0000。
public static byte[] Double2Real48(double d)
{
byte[] r48 = new byte[6];
byte[] da = BitConverter.GetBytes(d);
for (int i = 0; i < r48.Length; i++)
r48[i] = 0;
//Copy the negative flag
r48[5] |= (byte)(da[7] & 0x80);
//Get the expoent
byte b1 = (byte)(da[7] & 0x7f);
ushort n = (ushort)(b1 << 4);
byte b2 = (byte)(da[6] & 0xf0);
b2 >>= 4;
n |= b2;
if (n == 0)
return r48;
byte ex = (byte)(n - 1023);
r48[0] = (byte)(ex + 129);
//Copy the Mantissa
r48[5] |= (byte)((da[6] & 0x0f) << 3);//Get the last four bits
r48[5] |= (byte)((da[5] & 0xe0) >> 5);//Get the first three bits
r48[4] = (byte)((da[5] & 0x1f) << 3);//Get the last 5 bits
r48[4] |= (byte)((da[4] & 0xe0) >> 5);//Get the first three bits
r48[3] = (byte)((da[4] & 0x1f) << 3);//Get the last 5 bits
r48[3] |= (byte)((da[3] & 0xe0) >> 5);//Get the first three bits
r48[2] = (byte)((da[3] & 0x1f) << 3);//Get the last 5 bits
r48[2] |= (byte)((da[2] & 0xe0) >> 5);//Get the first three bits
r48[1] = (byte)((da[2] & 0x1f) << 3);//Get the last 5 bits
r48[1] |= (byte)((da[1] & 0xe0) >> 5);//Get the first three bits
return r48;
}
【问题讨论】:
-
这是正常的舍入误差,是意料之中的。并非所有浮点数都可以用二进制精确表示。如果您想要更精确,请使用
decimal,但此问题将仍然存在。 -
实际上,在这种情况下这可能不是问题 - 我刚刚重新阅读了您的问题,发现这些数字不是我想象的那样。
-
首先听起来你想对一个数字求平方,然后你用不正确的十进制表示替换这个数字,然后你发布一个似乎手动将数字加倍的方法...... 你想做什么?
-
@Chrisf: 0.229999 将是一个正常的舍入问题。 0.23999 要么是算法问题,要么是数据中的拼写错误。
-
@ChrisF 我的问题请帮助我
标签: c# asp.net double pascal type-conversion