-1

给定以毫升为单位的数量和 3 个包装尺寸(20 毫升、200 毫升和 1000 毫升),我想计算每个包装需要多少个才能满足总量。

例如

Amount = 3210ml
1000ml = 3 packs
200ml = 1 pack
20ml = 1 pack (always round up to nearest quantity)

这几乎就像一个找零计算器,我正在寻找正确的方法。

这是我的尝试

public class PackSizeCalculator
{
    private const int LargePackSize = 1000;
    private const int MediumPackSize = 200;
    private const int SmallPackSize = 20;

    public int LargePacks {get; set;}
    public int MediumPacks {get; set;}
    public int SmallPacks {get; set;}

    public  PackSizeCalculator(int amount)
    {
        int remainder = amount;

        while(remainder > 0) {
            if(remainder >= LargePackSize)
            {
                LargePacks = remainder / LargePackSize;
                remainder = remainder % LargePackSize;
            }
            else if(remainder >= MediumPackSize)
            {
                MediumPacks = remainder / MediumPackSize;
                remainder = remainder % MediumPackSize;
            }
            else if(remainder > SmallPackSize)
            {
                if(remainder % SmallPackSize == 0)
                {
                    SmallPacks = (remainder / SmallPackSize);
                }
                else {
                    SmallPacks = (remainder / SmallPackSize) + 1;
                }
                remainder = 0;
            }
            else {
                SmallPacks = 1;
                remainder = 0;
            }
        }
    }
}

这是一个很好的方法还是你会推荐一些不同的东西?

4

2 回答 2

1

像这样的东西:

const int LARGE_PACK = 1000;
const int MEDIUM_PACK = 200;
const int SMALL_PACK = 20;

int largePacks = (int)(Amount / LARGE_PACK);
int mediumPacks = (int)((Amount % LARGE_PACK) / MEDIUM_PACK);
int smallPacks = (int)ceil(((float)((Amount % LARGE_PACK) % MEDIUM_PACK) / SMALL_PACK));
于 2011-02-13T07:30:43.843 回答
0

你可以像这样创建一个函数:

struct Change
{
    public int  Large;
    public int  Medium;
    public int  Small;
}
private Change CalculateChange(int TotalAmount)
{
    Change result;
    result.Large = TotalAmount >= 1000 ? TotalAmount / 1000 : 0;
    result.Medium = TotalAmount % 1000 >= 200 ? (TotalAmount % 1000) / 200 : 0;
    result.Small = (TotalAmount % 1000) % 200 >= 20 ? ((TotalAmount % 1000) % 200) / 20 : 0;
    return result;
}

最后,您将获得更改结构类型的结果。

于 2011-02-13T07:57:07.827 回答