0
給定一個數量爲ml和3個包裝大小(20ml,200ml和1000ml),我想計算每個包裝需要多少個才能完成總量。在C中改變計算器的良好實現
E.g.
Amount =ml
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;
}
}
}
}
這是一個很好的方式去了解它,或者你會推薦什麼不同?
請發表您到目前爲止寫的代碼。 – 2011-02-13 07:25:55
沒有正確的方法來做到這一點。你的「問題」聽起來更像是「請爲我做」。這是大腦外包......你正在尋找一種算法,而不是真正的技術代碼/編程問題。這可能可能是一種跛腳懶惰的表現,因爲你至少應該提出你想到的預反思/算法替代方案。 – 2011-02-13 07:29:38