按照1美元等于6人民币汇率编写一个美元和人民币的双向兑换程序
时间: 2024-10-08 19:03:17 浏览: 54
java美元兑人民币汇率的工具类
按照1美元等于6人民币的固定汇率,我们可以创建一个简单的Python函数来进行双向兑换:
```python
def currency_converter(amount, from_currency="USD", to_currency="CNY"):
# 定义汇率
rate = {
"USD": 6, # 美元对人民币
"CNY": 1 / 6, # 人民币对美元
}
# 检查输入货币是否有效
if from_currency not in rate or to_currency not in rate:
return "无效的货币类型"
# 进行转换
converted_amount = amount * rate[from_currency]
# 根据目标货币返回结果
if to_currency == "USD":
return f"{amount} {from_currency} = {converted_amount:.2f} {to_currency}"
else:
return f"{amount} {from_currency} = {converted_amount:.2f} {to_currency}"
# 示例
print(currency_converter(100, "USD")) # 输出:100 USD = 600.00 CNY
print(currency_converter(600, "CNY", "USD")) # 输出:600.00 CNY = 100.00 USD
阅读全文