C# 中变更计算器的良好实现
给定毫升数量和 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;
}
}
}
}
这是一个好方法吗?或者您会推荐一些不同的方法吗?
Given an amount in ml and 3 pack sizes (20ml, 200ml and 1000ml) I'd like to calculate how many of each packs are needed to fulfill the total amount.
E.g.
Amount = 3210ml
1000ml = 3 packs
200ml = 1 pack
20ml = 1 pack (always round up to nearest quantity)
This is pretty much just like a change calculator, and I'm looking for the right way to do it.
Here's my attempt
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;
}
}
}
}
Is this a good way to go about it or would you recommend something different?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样的东西:
Something like this:
您可以创建这样的函数:
最后您将得到更改结构类型的结果。
You can create a function like this:
At the end you will have your result of Change struct Type.