简体   繁体   English

舍入浮点值

[英]Rounding Floating point Values

I was on a task of porting C++ code to C#. 我的任务是将C ++代码移植到C#。 There was a bug reported by client in my code. 客户在我的代码中报告了一个错误。 When I did debugging, here is what I got... 当我进行调试时,这就是我得到的...

C++ Code: C ++代码:

double d = -0.0000000000018736038338473693;
String temp = String(SimpleRoundTo(d, -12))); // SimpleRoundTo() is from delphi
// temp is having -1E-12

C# Code: C#代码:

double d = -0.0000000000018736038338473693;
string temp = (Math.Round(d, 12)).ToString();
// temp is having -2E-12

I did check the overloads by Math.Round(), not getting how to get the same result. 我确实通过Math.Round()检查了重载,但没有得到如何获得相同的结果。

The answer that the C++ version is giving is just plain wrong. C ++版本给出的答案是完全错误的。 That should be obvious. 那应该很明显。 It's clear that 2E-12 is the correct answer since SimpleRoundTo , just like Math.Round , rounds to nearest. 很明显, 2E-12是正确的答案,因为SimpleRoundTo就像Math.Round一样四舍五入到最接近的值。

So, if you wish to reproduce the erroneous output of the C++ version in C# you'll need to translate the Delphi RTL code to C#. 因此,如果您希望在C#中重现C ++版本的错误输出,则需要将Delphi RTL代码转换为C#。 That would involve working out exactly what SimpleRoundTo and the String() conversion does. 那将涉及确切地计算出SimpleRoundToString()转换的作用。 Or p/invoke to a C++ DLL. 或p /调用C ++ DLL。

I would tackle this by trying to work out what the original code is intended to do. 我将通过尝试解决原始代码的意图来解决此问题。 Express this in a mathematical way rather than in terms of the RTL functions. 用数学方式而不是RTL函数表示。 Once you have a clear specification of what you intend the code to do, code it in C# using the natural C# mechanisms. 一旦清楚地说明了代码的用途,请使用自然的C#机制在C#中进行编码。 In other words, don't attempt a literal translation because one probably does not exist. 换句话说,不要尝试文字转换,因为可能不存在文字转换。 Instead understand the intent of the original code and implement it from scratch in C#. 而是了解原始代码的意图,并在C#中从头开始实现它。

Looking at your code you perform rounding, and then convert to text. 查看您的代码,执行四舍五入,然后转换为文本。 I would be looking for an approach that performed the rounding as part of the conversion to text. 我将寻找一种方法,该方法在将文本转换为文本的过程中进行了四舍五入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM