用货币交易时,经常出现找零钱的问题,如何找零钱能使货币数量最少,用贪婪算法编写一程序
时间: 2023-06-04 12:07:35 浏览: 52
为您提供一个基于贪心算法的找零钱程序:
```python
def find_change(denominations, amount):
change = []
total = 0
i = len(denominations) - 1
while i >= 0 and total != amount:
while total + denominations[i] <= amount:
total += denominations[i]
change.append(denominations[i])
i -= 1
return change
denominations = [1, 5, 10, 50, 100]
amount = 68
change = find_change(denominations, amount)
print(change)
```
程序的执行结果为:`[50, 10, 5, 1, 1, 1]`,表示找零钱时使用了两个 50 元、一个 10 元、一个 5 元和三个 1 元,总共找出了 68 元,使得货币数量最少。
该程序的贪心策略是每次使用面额最大的钱币,并将其不断累加,直到无法再添加为止。由于每次使用的面额最大,因此能够使得货币数量最少。
相关问题
贪婪算法找零钱python
可以使用贪心算法解决找零钱问题,即每次找最大面额的硬币,直到总金额减为0。以下是 Python 代码示例:
```python
def greedy_coin_change(amount, coins):
coins.sort(reverse=True)
count = 0
for coin in coins:
while amount >= coin:
amount -= coin
count += 1
return count
```
其中,`amount` 是需要找零的金额,`coins` 是可用的硬币面额列表。函数返回最少需要找的硬币数量。
用c语言写一个找零钱的程序
好的,我可以回答这个问题。以下是一个用C语言编写的找零钱程序示例:
```
#include <stdio.h>
int main() {
int total, cost, change;
printf("请输入总金额:");
scanf("%d", &total);
printf("请输入商品金额:");
scanf("%d", &cost);
change = total - cost;
printf("找零:%d\n", change);
return 0;
}
```
注意:此代码可能需要进行优化和错误处理。