编写程序,实现两种货币的自由转换
时间: 2024-06-08 18:11:45 浏览: 159
以下是Python实现两种货币自由转换的程序:
```python
# 定义货币汇率
usd_to_rmb = 6.6
eur_to_rmb = 7.8
# 定义转换函数
def currency_converter(amount, from_currency, to_currency):
if from_currency == "USD" and to_currency == "RMB":
converted_amount = amount * usd_to_rmb
elif from_currency == "EUR" and to_currency == "RMB":
converted_amount = amount * eur_to_rmb
elif from_currency == "RMB" and to_currency == "USD":
converted_amount = amount / usd_to_rmb
elif from_currency == "RMB" and to_currency == "EUR":
converted_amount = amount / eur_to_rmb
else:
converted_amount = 0
print("不支持的货币转换")
return round(converted_amount, 2)
# 测试转换函数
print(currency_converter(100, "USD", "RMB")) # 660.0
print(currency_converter(100, "EUR", "RMB")) # 780.0
print(currency_converter(660, "RMB", "USD")) # 100.0
print(currency_converter(780, "RMB", "EUR")) # 100.0
print(currency_converter(100, "USD", "JPY")) # 不支持的货币转换
```
在这个程序中,我们首先定义了两种货币之间的汇率(美元对人民币和欧元对人民币)。然后我们定义了一个函数`currency_converter`,它接受三个参数:转换金额、原始货币和目标货币。函数根据原始货币和目标货币的不同,计算出转换后的金额,并返回结果。最后我们使用几个例子测试了这个转换函数。
阅读全文