我有一个名为“sum”的小数,其值为 5824088.999120m
,但是当我尝试将其四舍五入到 3 位小数时,我得到的是 5824088.998m
而不是 >5824088.999m
。它递减而不是留下 5824088.999m
。
这是为什么呢?这是我的代码:
List<decimal> quantityList = QuantityList();
List<decimal> priceList = PriceList();
decimal destination = 5824088.999M;
decimal sum = 0M;
bool lifesaver = false;
for (int x = 0; x < priceList.Count; x++)
{
sum = 0M;
for (int i = 0; i < 3500; i++)
{
priceList[x] += 0.001M;
sum = 0M;
for (int y = 0; y < priceList.Count; y++)
{
decimal multipleProduct = priceList[y] * quantityList[y];
sum = sum + multipleProduct;
Console.WriteLine(priceList[y] + " " + quantityList[y]);
sum = Math.Round(sum, 3);
Console.WriteLine("Sum: " + sum);
Console.ReadKey();
Console.WriteLine();
}
if (sum == destination)
{
Console.WriteLine("The new number is " + priceList[x] + " and it is the {0} element!", x);
lifesaver = true;
break;
}
else if (sum > destination)
{
Console.WriteLine("Limit exceeded!");
}
if (i == 3499)
{
priceList[x] -= 3.500M;
}
if (lifesaver == true)
{
break;
}
}//Second for loop
if (lifesaver == true)
{
break;
}
}//Main for loop
列表采用另一种方法。
最佳答案
您似乎有舍入错误累积,因此总数是错误的:
for (int y = 0; y < priceList.Count; y++) {
...
sum = Math.Round(sum, 3); // <- this accumulates round up errors
...
}
假设 priceList
包含
priceList = new List<Decimal>() {
1.0004M, 1.0004M, 1.0004M};
而quantityList
全为1; 总和
将为
1.000M, 2.000M, 3.000M
而实际总数为
Math.Round(1.0004M + 1.0004M + 1.0004M, 3)
3.001M。 可能的补救措施是不提前四舍五入:
for (int y = 0; y < priceList.Count; y++) {
...
//DONE: comment out this: no premature rounding (within the loop)
// sum = Math.Round(sum, 3);
//DONE: but format out when printing out
Console.WriteLine("Sum: {0:F3}", sum);
...
}
// round up (if you want) after the loop
sum = Math.Round(sum, 3);
关于c# - 小数未正确舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37068481/