天天看点

习题4-5 换硬币 (20分)(难点是怎么按照大小顺序排序)

将一笔零钱换成5分、2分和1分的硬币,要求每种硬币至少有一枚,有几种不同的换法?

输入格式:

输入在一行中给出待换的零钱数额x∈(8,100)。

输出格式:

要求按5分、2分和1分硬币的数量依次从大到小的顺序,输出各种换法。每行输出一种换法,格式为:“fen5:5分硬币数量, fen2:2分硬币数量, fen1:1分硬币数量, total:硬币总数量”。最后一行输出“count = 换法个数”。

输入样例:

13
           

输出样例:

fen5:2, fen2:1, fen1:1, total:4
fen5:1, fen2:3, fen1:2, total:6
fen5:1, fen2:2, fen1:4, total:7
fen5:1, fen2:1, fen1:6, total:8
count = 4
           

参考答案:

#include<stdio.h>
int main()
{
	int i, j, k;					//循环变量 
	int count_5, count_2, count_1;	//硬币最大数量
	int total_money, total_count, count = 0;
	scanf("%d", &total_money);
	count_1 = total_money / 1;
	count_2 = total_money / 2;
	count_5 = total_money / 5; 
	for(i = count_5; i > 0; i--)
	{
		for(j = count_2; j > 0; j--)
		{
			for(k = count_1; k > 0; k--)
			{
				if(total_money == 5 * i + 2 * j + 1 * k)
				{
					total_count = i + j + k;
					printf("fen5:%d, fen2:%d, fen1:%d, total:%d\n", i, j, k, total_count);
					count++;
				}
			}
		}
	}
	printf("count = %d\n",count);
	return 0; 
}
           

继续阅读