C#乘法错误(双精度)[从C#论坛转发] [英] C# Multiplication error (double) [ Repost from C# forum ]

查看:237
本文介绍了C#乘法错误(双精度)[从C#论坛转发]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我做一些简单的事情时,例如

When I do some thing simple like

double result = 3.1*4.1;



结果是12.709999999999999

我本来希望12.710000000000000




the result is 12.709999999999999

I would have expected 12.710000000000000


Is this normal for C#?

推荐答案

这是正常的,浮点数不能始终表示值的准确表示.如果要显示四舍五入的数字,则ToString()方法提供了该功能.
This is normal, floating point numbers cannot always depict an accurate representation of a value. If you want to display the number rounded then the ToString() method offers that capability.


有一个经典文本,
There is a classic text, What Every Computer Scientist Should Know About Floating-Point Arithmetic[^] by David Goldberg that should help you understand what''s happening here. It''s not specific to C#, but rather the IEEE 754 standard for floating-point numbers that C# uses.

Suffice to say, it is normal, merely a common rounding error, similar to what you might have encountered in grade school when trying to represent the result of an expression such as 10 / 3 in decimal form...


我遇到了同样的问题.我发现的唯一解决方案是将值转换为小数,然后将它们相乘,然后转换为Double.那是昂贵的,但是如果没有其他解决方案可用,那就可以接受.
I had the same problem. The only solution I found is to convert the values to decimals, multiply them and after that convert to Double. That''s expensive, but if no other solution is available, is acceptable.


这篇关于C#乘法错误(双精度)[从C#论坛转发]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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