using System; using System.Collections.Generic; using System.Text; namespace Ctest { class Program { static void Main(string[] args) { float f = 0; for (int i = 0; i < 1000; i++) { f += 0.1f; } Console.WriteLine(f); //99.99905 double d = 0; for (int i = 0; i < 1000; i++) { d += 0.1; } Console.WriteLine(d); //99.9999999999986 Decimal dec = new Decimal(0); for (int i = 0; i < 1000; i++) { dec = Decimal.Add(dec,new Decimal(0.1)); } Console.WriteLine(dec); //100.0 } } }
最初用了循环10次试验,发现没有问题,还以为C#会没有问题,谁知道原理它内部的实现与java不同,呵呵,隐藏的很深啊!
而且不像java,在+=中需要指定0.1f,呵呵。
本文通过C#代码演示了使用不同数值类型(float、double、Decimal)进行累加操作时的精度表现,揭示了浮点数运算中的精度损失问题,并展示了Decimal类型在财务计算等场景中的优势。

被折叠的 条评论
为什么被折叠?



