8.9.3 实现CBox类(10)
该问题的第二部分是使用3个嵌套的for循环解决的。这些循环在m_Length、m_Width和m_Height的允许范围内迭代,从而评估所有可能的组合。可以将这些组合全部输出到屏幕上,但因为涉及的组合多达200个,而我们可能只对其中一小部分感兴趣,所以程序中使用一条if语句来识别那些我们感兴趣的选项。仅当纸板箱中没有浪费的空间、当前试验的糖果盒中没有浪费的空间,并且该糖果盒至少包含30块糖果时,if表达式才是true。
示例说明
该程序的输出如下:
- There are 42 candies per candy box
- For the standard boxes there are 144 candy boxes per carton
- with 648 cubic inches wasted.
- CUSTOM CANDY BOX ANALYSIS (No Waste)
- Trial Box L = 5 W = 4.5 H = 2
- Trial Box contains 30 candies and a carton contains 216 candy boxes.
- Trial Box L = 5 W = 4.5 H = 2
- Trial Box contains 30 candies and a carton contains 216 candy boxes.
- Trial Box L = 6 W = 3 H = 2.5
- Trial Box contains 30 candies and a carton contains 216 candy boxes.
- Trial Box L = 6 W = 4.5 H = 2
- Trial Box contains 36 candies and a carton contains 180 candy boxes.
- Trial Box L = 6 W = 4.5 H = 2.5
- Trial Box contains 45 candies and a carton contains 144 candy boxes.
- Trial Box L = 6 W = 5 H = 1.5
- Trial Box contains 30 candies and a carton contains 216 candy boxes.
- Trial Box L = 6 W = 5 H = 2
- Trial Box contains 40 candies and a carton contains 162 candy boxes.
- Trial Box L = 6 W = 5 H = 2.5
- Trial Box contains 50 candies and a carton contains 129 candy boxes.
- Trial Box L = 7.5 W = 3 H = 2
- Trial Box contains 30 candies and a carton contains 216 candy boxes.
因为嵌套循环中既评估长5英寸、宽4.5英寸的箱子,也评估长4.5英寸、宽5英寸的箱子,所以得到一个重复的解决方案。因为CBox类的构造函数能够确保长度不小于宽度,所以这两个答案是相同的。可以包括一些避免出现重复方案的其他逻辑,但这样做几乎没有效果。如果愿意,那么您可以将其当作一道练习题试一下。