双字节类型转换错误

编程入门 行业动态 更新时间:2024-10-12 14:21:22
本文介绍了双字节类型转换错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

通过数学运算从字节转换为 double 时,我得到了预期的结果。 执行相同的数学运算来反转值的变化,只要我保持 double 类型,就会产生正确的值。 但是最后我将 double result转换回字节值,转换结果不正确1

When performing conversion from byte to double by mathematical operations I've got expected result. Performing the same mathematical operations to reverse the changes in value, results in correct value as long as I keep double type. But when at the end I converts double result back to byte value the conversion results is incorrect by 1.

只有一些字节值才是这种情况。

This is the case only for some byte values.

确切的过程:

byte b = 82; Console.WriteLine(b); // initial byte value double d = (b / 100.0) + 2.00; Console.WriteLine(d); // 82 / 100 -> 0.82 + 2.00 -> 2.82 OK double dt = d - 2.00; Console.WriteLine(dt); // 2.82 - 2.0 -> 0.82 OK double db = dt * 100.0; Console.WriteLine(db); // 0.82 * 100 -> 82 (double) OK byte dbb = (byte)db; Console.WriteLine(dbb); // (byte)82 -> 81 ERROR ERROR ERROR b = Byte.Parse(db.ToString()); Console.WriteLine(b); // 82 -> "82" and to byte OK

为什么会发生? double 结果在逗号后没有任何值。

Why it is happening? The double result does not have any values after comma.

推荐答案

如果您调试代码,您将看到发生了什么:

if you debug your code you will see what is going on:

double d = (b / 100.0) + 2.00; Console.WriteLine(d)// => d = 2.82 double dt = d - 2.00; Console.WriteLine(dt) // => dt = 0.81999999999999984 double db = dt * 100.0; Console.WriteLine(db) // => db = 81.999999999999986 byte dbb = (byte)db; Console.WriteLine(dbb) //=> dbb = 81, because Byte is cut off after the ","

之后切换字节如果您使用十进制而不是双重,它将会奏效。

If you use decimal instead of double it will work out.

请参阅: stackoverflow/questions/2741903/c-sharp-4-double-minus-double -giving-precision-problems

使其完成:

decimal d = (b / 100.0m) + 2.00m; Console.WriteLine(d); decimal dt = d - 2.00m; Console.WriteLine(dt); decimal db = dt * (decimal)100.0; Console.WriteLine(db); byte dbb = (byte)db; Console.WriteLine(dbb);

您可以转换(十进制)或使用值后面的m。

You can either cast (decimal) or use the "m" behind the value.

更多推荐

双字节类型转换错误

本文发布于:2023-10-10 21:28:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1479797.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字节   错误   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!