设计一段代码能够让美元人民币与日元相互转换
时间: 2023-05-13 16:06:51 浏览: 127
以下是一段 Python 代码,可以实现美元、人民币和日元之间的相互转换:
```python
def convert_currency(amount, from_currency, to_currency):
# 汇率表
exchange_rates = {
('USD', 'CNY'): 6.47,
('CNY', 'USD'): 0.15,
('USD', 'JPY'): 109.44,
('JPY', 'USD'): 0.0091,
('CNY', 'JPY'): 17.79,
('JPY', 'CNY'): 0.056
}
# 转换
if (from_currency, to_currency) in exchange_rates:
rate = exchange_rates[(from_currency, to_currency)]
result = amount * rate
return result
elif (to_currency, from_currency) in exchange_rates:
rate = exchange_rates[(to_currency, from_currency)]
result = amount / rate
return result
else:
return None
# 测试
print(convert_currency(100, 'USD', 'CNY')) # 647.0
print(convert_currency(100, 'CNY', 'USD')) # 15.38
print(convert_currency(100, 'USD', 'JPY')) # 10944.0
print(convert_currency(100, 'JPY', 'USD')) # 0.91
print(convert_currency(100, 'CNY', 'JPY')) # 1779.0
print(convert_currency(100, 'JPY', 'CNY')) # 5.6
```
使用方法:调用 `convert_currency(amount, from_currency, to_currency)` 函数,其中 `amount` 是要转换的金额,`from_currency` 是原始货币,`to_currency` 是目标货币。例如,`convert_currency(100, 'USD', 'CNY')` 将返回 647.0,表示将 100 美元转换为人民币。
阅读全文