2011-02-13 59 views
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; 
      } 
     } 
    } 
} 

這是一個很好的方式去了解它,或者你會推薦什麼不同?

+0

請發表您到目前爲止寫的代碼。 – 2011-02-13 07:25:55

+1

沒有正確的方法來做到這一點。你的「問題」聽起來更像是「請爲我做」。這是大腦外包......你正在尋找一種算法,而不是真正的技術代碼/編程問題。這可能可能是一種跛腳懶惰的表現,因爲你至少應該提出你想到的預反思/算法替代方案。 – 2011-02-13 07:29:38

回答

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)); 
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; 
} 

在最後,你將有你的更改結構類型的結果。