gpt4 book ai didi

c# - 尝试计算框的分数时的小数精度损失

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:04:41 24 4
gpt4 key购买 nike

我有一个场景,我有一个包含 3 个 jar 头的标准盒子。为了显示和查询的目的,我必须以其标准配置的小数位来报告。不可能说 1 箱 3 jar ,1 箱 2 jar ...等等

例如,一开始我会有1盒3 jar
然后我移除 1 个 jar 头,得到 0.66 个 3 个 jar 头的重复框
然后,我再移除 1 个 jar 头,导致 0.33 个 3 个 jar 头的重复框
然后我取出最后一个 jar 头,得到 0.0000000000000000000000000001 一盒 3 jar

当我取出最后一个 jar 头时,我希望该值为 0 盒 3 jar ,因为现在每个 jar 头都已从原始盒子中取出。我很欣赏由于在处理有限位数时无法重复表示 0.33 而导致精度损失。

问题:对于在需要使用舍入(可能是财务)的系统方面有更多经验的人,我有什么选择来处理这个问题?你会如何让最后一个的移除意味着盒子不再存在?

编辑:
到底。我使用了 Loren Pechtel 的建议并存储了 jar 头的数量,然后当我需要显示有多少个标准盒子时,我将 jar 头总数除以标准盒子中的 jar 头数量,这仍然给出了递归结果,但这对于报告来说很好事物的一面。

这里有一些代码,我希望它能帮助更多地概述问题:-

     static void Main(string[] args)
{
var box = new StandardBox(3);
var boxDetail = new BoxDetail(1.0m, box);

var allBoxes = new AllBoxes();
allBoxes.AddBox(boxDetail);
allBoxes.RemoveItemFromBox(boxDetail, 1.0m);
Console.WriteLine(allBoxes);
allBoxes.RemoveItemFromBox(boxDetail, 1.0m);
Console.WriteLine(allBoxes);
allBoxes.RemoveItemFromBox(boxDetail, 1.0m);
Console.WriteLine(allBoxes);
Console.ReadLine();
}
}

public class StandardBox
{
private decimal _quantity;
public StandardBox(decimal quantity){_quantity = quantity;}
public decimal Quantity {get { return _quantity; }}
}

public class BoxDetail
{
private decimal _quantity;
private StandardBox _box;

public BoxDetail(decimal quantity, StandardBox box)
{
_quantity = quantity;
_box = box;
}

public void RemoveItem(decimal quantity)
{
var newQuantity = quantity / _box.Quantity;
_quantity = _quantity - newQuantity;
}

public override string ToString()
{
return _quantity.ToString() + " of " + _box.Quantity.ToString();
}
}

public class AllBoxes
{
private List<BoxDetail> allBoxes = new List<BoxDetail>();

public AllBoxes(){}

public void AddBox(BoxDetail box){allBoxes.Add(box);}

public void RemoveItemFromBox(BoxDetail box, decimal quantity)
{
var boxDetailLineToModify = allBoxes.Find(b => b.Equals(box));
boxDetailLineToModify.RemoveItem(quantity);
}

public override string ToString()
{
var results = string.Empty;
foreach (var box in allBoxes)
{
results += box.ToString() + "\n";
}
return results;
}
}

最佳答案

我对此类问题的处理方法是不做。

在涉及财务方面尤其如此。

财务方面的事情通常很容易处理——用几分钱而不是美元来完成你所有的工作。

我对你的问题的第一 react 是存储 jar 头而不是 jar 头盒。

关于c# - 尝试计算框的分数时的小数精度损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9541458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com