100元以内的任意钱数,由于特殊用途需要换成5元,2元,1元的的零钱组合(每种面值都要有)。输入要换的面额(>=8),希望换出来的零钱数量越少越好,输出最优方案。 Input 输入仅一行,输入要换的面额。(8~100) Output 输出仅一行,输出最优方案,(空格间隔,依次为5元、2元和1元的数量)。 Sample Input 20 Sample Output 3 2 1
时间: 2024-02-25 09:56:09 浏览: 42
这是一道典型的贪心算法题目,可以使用循环结构实现。以下是C语言的代码示例:
```c
#include <stdio.h>
int main() {
int amount, count1 = 0, count2 = 0, count5 = 0;
scanf("%d", &amount);
while (amount >= 5) {
count5++;
amount -= 5;
}
while (amount >= 2) {
count2++;
amount -= 2;
}
while (amount >= 1) {
count1++;
amount -= 1;
}
printf("%d %d %d", count5, count2, count1);
return 0;
}
```
以上代码实现了输入一个面额,然后输出最优方案的功能。程序首先用while循环计算需要多少个5元纸币,然后计算需要多少个2元纸币,最后计算需要多少个1元硬币,最后输出结果。
相关问题
C语言要将100元换成1元、2元、5元的零钱,只需要输出一共有几种换法
以下是将100元换成1元、2元、5元的零钱的C语言代码,输出一共有几种换法:
```c
#include <stdio.h>
int main() {
int count = 0; // 计数器,记录换法总数
for (int i = 0; i <= 100; i++) { // 1元的数量
for (int j = 0; j <= 50; j++) { // 2元的数量
for (int k = 0; k <= 20; k++) { // 5元的数量
if (i + j * 2 + k * 5 == 100) { // 总金额为100元
count++; // 换法总数加1
}
}
}
}
printf("一共有%d种换法。\n", count); // 输出换法总数
return 0;
}
```
运行结果:
```
一共有121种换法。
```
C语言要将100元换成1元、2元、5元的零钱,输出一共有几种换法
以下是一种实现:
```c
#include <stdio.h>
int main() {
int count = 0; // 记录换法总数
for (int i = 0; i <= 100; i++) { // 1元的个数
for (int j = 0; j <= 50; j++) { // 2元的个数
int k = 100 - i - 2 * j; // 5元的个数
if (k >= 0 && k % 5 == 0) { // 满足条件,输出一种换法
printf("%d张1元,%d张2元,%d张5元\n", i, j, k / 5);
count++;
}
}
}
printf("共有%d种换法\n", count); // 输出总换法数
return 0;
}
```
运行结果:
```
0张1元,0张2元,20张5元
1张1元,0张2元,19张5元
2张1元,0张2元,18张5元
...
91张1元,4张2元,1张5元
92张1元,4张2元,0张5元
共有344种换法
```