我尝试了等效的Michael Meadows EDIT 2,但在 VB.NET 中得到了不同的结果。(具体来说,Double
和Decimal
结果都是 600000.0238418580。)
我已经确定差异在于Single
存储到 a 中的除法的编译时准确性Single
以及当您强制除法在运行时发生时。
因此,THREE_FIFTHS
并vTHREE_FIFTHS
为asDecimal
求和提供不同的结果:
const ONE_MILLION As Integer = 1000000
Dim THREEsng As Single = 3!
Dim FIVEsng As Single = 5!
Dim vTHREE_FIFTHS As Single = THREEsng / FIVEsng
const THREE_FIFTHS As Single = 3! / 5!
Console.WriteLine("Three Fifths: {0}", THREE_FIFTHS.ToString("F10"))
Dim asSingle As Single = 0!
Dim asDouble As Double = 0#
Dim asDecimal As Decimal = 0@
For i As Integer = 1 To ONE_MILLION
asSingle += CSng(THREE_FIFTHS)
asDouble += CDbl(THREE_FIFTHS)
asDecimal += CDec(THREE_FIFTHS)
Next
Console.WriteLine("Six Hundred Thousand: {0:F10}", THREE_FIFTHS * ONE_MILLION)
Console.WriteLine("Single: {0}", asSingle.ToString("F10"))
Console.WriteLine("Double: {0}", asDouble.ToString("F10"))
Console.WriteLine("Decimal: {0}", asDecimal.ToString("F10"))
Console.WriteLine("vThree Fifths: {0}", vTHREE_FIFTHS.ToString("F10"))
asSingle = 0!
asDouble = 0#
asDecimal = 0@
For i As Integer = 1 To ONE_MILLION
asSingle += CSng(vTHREE_FIFTHS)
asDouble += CDbl(vTHREE_FIFTHS)
asDecimal += CDec(vTHREE_FIFTHS)
Next
Console.WriteLine("Six Hundred Thousand: {0:F10}", vTHREE_FIFTHS * ONE_MILLION)
Console.WriteLine("Single: {0}", asSingle.ToString("F10"))
Console.WriteLine("Double: {0}", asDouble.ToString("F10"))
Console.WriteLine("Decimal: {0}", asDecimal.ToString("F10"))
突出显示差异的结果是:
Three Fifths: 0.6000000000
Six Hundred Thousand: 600000.0000000000
Single: 599093.4000000000
Double: 600000.0238418580
Decimal: 600000.0238418580
vThree Fifths: 0.6000000000
Six Hundred Thousand: 600000.0000000000
Single: 599093.4000000000
Double: 600000.0238418580
Decimal: 600000.0000000000
我的问题是,你能让 VB.NET 得到一个Const Single
与运行时结果等效的表达式吗?(即产生THREE_FIFTHS
与 相同的结果vTHREE_FIFTHS
。)