找零钱问题贪心算法c语言代码
时间: 2023-12-25 10:28:21 浏览: 246
以下是C语言实现找零钱问题的贪心算法代码,该算法从最大面额硬币开始尝试找零,以减少硬币数量:
```c
#include <stdio.h>
void findMinCoins(int coins[], int n, int amount)
{
int coinCount[n];
for (int i = 0; i < n; i++) {
coinCount[i] = 0;
}
for (int i = n - 1; i >= ; i--) {
while (amount >= coins[i]) {
amount -= coins[i];
coinCount[i }
}
printf("找零的硬币数量为:\n");
for (int i = n - 1; i >= 0; i--) {
if (coinCount[i] != 0) {
printf("%d 个 %d 元硬币\n", coinCount[i], coins[i]);
}
}
}
int main()
{
int coins[] = { 1, 2, 5, 10, 20, 50, 100 };
int n = sizeof(coins) / sizeof(coins[0]);
int amount = 78;
findMinCoins(coins, n, amount);
return 0;
}
```
阅读全文