我正在尝试确定C# ulong数字中的位数,我正在尝试使用一些数学逻辑而不是使用ToString().Length来实现。我还没有对这两种方法进行基准测试,但已经看到其他帖子使用System.Math.Floor(System.Math.Log10(number)) + 1来确定数字的位数。似乎很好用,直到从999999999999997过渡到999999999999998时,我开始得到错误的计数。
有人遇到过这个问题吗?
我曾看到类似的Java强调的帖子@Why log(1000)/log(10) isn't the same as log10(1000)?,还有一篇帖子@How to get the separate digits of an int number?,它指出了如何使用%运算符可能以更多的代码实现相同的功能。
以下是我用来模拟此问题的代码。
有人遇到过这个问题吗?
我曾看到类似的Java强调的帖子@Why log(1000)/log(10) isn't the same as log10(1000)?,还有一篇帖子@How to get the separate digits of an int number?,它指出了如何使用%运算符可能以更多的代码实现相同的功能。
以下是我用来模拟此问题的代码。
Action<ulong> displayInfo = number =>
Console.WriteLine("{0,-20} {1,-20} {2,-20} {3,-20} {4,-20}",
number,
number.ToString().Length,
System.Math.Log10(number),
System.Math.Floor(System.Math.Log10(number)),
System.Math.Floor(System.Math.Log10(number)) + 1);
Array.ForEach(new ulong[] {
9U,
99U,
999U,
9999U,
99999U,
999999U,
9999999U,
99999999U,
999999999U,
9999999999U,
99999999999U,
999999999999U,
9999999999999U,
99999999999999U,
999999999999999U,
9999999999999999U,
99999999999999999U,
999999999999999999U,
9999999999999999999U}, displayInfo);
Array.ForEach(new ulong[] {
1U,
19U,
199U,
1999U,
19999U,
199999U,
1999999U,
19999999U,
199999999U,
1999999999U,
19999999999U,
199999999999U,
1999999999999U,
19999999999999U,
199999999999999U,
1999999999999999U,
19999999999999999U,
199999999999999999U,
1999999999999999999U
}, displayInfo);
提前感谢
Pat
Log10
函数时得到不正确的结果是有道理的,因为该函数使用double
类型,无法精确表示非常大的整数(请参见http://en.wikipedia.org/wiki/Double_precision_floating-point_format)。 - JustinToString().Length
有什么特别错误的地方。此外,只要签名正确,您可以将您的Action
更改为普通方法。 - Daniel T.