換硬幣問題
* 編程求:把一張1元的鈔票換成5分,2分和1分的硬幣,要求每種至少一枚,
* 並且所換硬幣數不超過30枚。請問有哪幾種換法。
*
* 需求分析: 1.1元=100分
* 2.三元方程求解不等式
* 5x+2y+z = 100;
* x+y+z <=30;
* x,y,z>=1;
以下是C#代碼實現:
//三層for循環中定義三個變量fiveCentCoin,twoCentCoin,oneCentCoin分別表示5分,2分,1分硬幣的數量窮舉
//定義一個計數器統計有多少種換法
int count = 0;
//第一層for控制5分硬幣數量
for (int fiveCentCoin = 1; fiveCentCoin <= 18; fiveCentCoin++)
{
//第二層for控制2分硬幣數量
for (int twoCentCoin = 1; twoCentCoin <= 28; twoCentCoin++)
{
//第三層for控制1分硬幣數量
for (int oneCentCion = 1; oneCentCion <= 28; oneCentCion++)
{
if (fiveCentCoin + twoCentCoin + oneCentCion <= 30
&& 5*fiveCentCoin + 2*twoCentCoin + oneCentCion == 100)
{
//計數且輸出合適方案
count++;
Console.WriteLine("第{0}種換法:{1}枚5分,{2}枚2分,{3}枚1分;",count,fiveCentCoin,twoCentCoin,oneCentCion);
}
}
}
}
//輸出總共有多好種方案
Console.WriteLine("總共有{0}中方案。",count);
好了,這個問題就到這裏,有疑問的可以私信博主。
純手打。
給個關注唄!