C++基础货币转换器仅USD转英镑生效,其他币种转换失效求助
问题分析与修复方案
核心错误原因
你的代码里所有判断货币类型的地方都用了<=来比较字符串,这是完全错误的。C++中字符串的<=是按字典序(字母顺序)比较,不是判断是否相等。比如:
- "Euro" 的字典序比 "Usd"、"Pound"、"Peso" 都小,所以当你输入
s = "Euro"时,s <= Euro、s <= Usd、s <= Pound、s <= Peso都会返回true,导致多个外层if块同时执行,逻辑彻底混乱。 - 只有USD转英镑碰巧生效,是因为字典序的巧合让对应条件刚好符合,但这完全是偶然。
修复后的完整代码
#include <iostream> #include <string> using namespace std; int main() { const string Euro = "Euro"; const string Usd = "Usd"; const string Pound = "Pound"; const string Peso = "Peso"; string from_currency; string to_currency; float amount; float converted_amount; cout << "请选择要转换的货币类型:Usd,Euro,Pound,Peso" << endl; cin >> from_currency; cout << "请选择转换目标货币:" << endl; cin >> to_currency; cout << "请输入" << from_currency << "的金额:" << endl; cin >> amount; // 欧元转其他货币 if (from_currency == Euro) { if (to_currency == Usd) { converted_amount = amount * 1.02; cout << "转换后金额:" << converted_amount << " 美元" << endl; } else if (to_currency == Pound) { converted_amount = amount * 0.85; cout << "转换后金额:" << converted_amount << " 英镑" << endl; } else if (to_currency == Peso) { converted_amount = amount * 131.82; cout << "转换后金额:" << converted_amount << " 比索" << endl; } else { cout << "不支持的目标货币类型" << endl; } } // 美元转其他货币 else if (from_currency == Usd) { if (to_currency == Euro) { converted_amount = amount / 1.02; cout << "转换后金额:" << converted_amount << " 欧元" << endl; } else if (to_currency == Pound) { converted_amount = amount / 1.2; cout << "转换后金额:" << converted_amount << " 英镑" << endl; } else if (to_currency == Peso) { converted_amount = amount * 129.07; cout << "转换后金额:" << converted_amount << " 比索" << endl; } else { cout << "不支持的目标货币类型" << endl; } } // 英镑转其他货币 else if (from_currency == Pound) { if (to_currency == Usd) { converted_amount = amount * 1.2; cout << "转换后金额:" << converted_amount << " 美元" << endl; } else if (to_currency == Euro) { converted_amount = amount * 1.18; cout << "转换后金额:" << converted_amount << " 欧元" << endl; } else if (to_currency == Peso) { converted_amount = amount * 154.92; cout << "转换后金额:" << converted_amount << " 比索" << endl; } else { cout << "不支持的目标货币类型" << endl; } } // 比索转其他货币 else if (from_currency == Peso) { if (to_currency == Usd) { converted_amount = amount * 0.0077; cout << "转换后金额:" << converted_amount << " 美元" << endl; } else if (to_currency == Pound) { converted_amount = amount * 0.0065; cout << "转换后金额:" << converted_amount << " 英镑" << endl; } else if (to_currency == Euro) { converted_amount = amount * 0.0076; cout << "转换后金额:" << converted_amount << " 欧元" << endl; } else { cout << "不支持的目标货币类型" << endl; } } else { cout << "不支持的源货币类型" << endl; } return 0; }
关键修复点
- 把所有字符串比较的
<=替换为==,正确判断货币类型是否匹配。 - 外层条件用
else if替代独立的if,确保每次只有一个货币转换逻辑块执行,避免多个块同时触发。 - 内层条件也改用
else if,并增加错误提示,处理用户输入无效货币的情况。 - 修正了非标准的
void main()为标准的int main(),并添加return 0;符合C++规范。 - 变量名更具可读性(比如
s改为from_currency,c改为to_currency),方便后续维护。
内容的提问来源于stack exchange,提问作者Flame
相关产品推荐
相关产品推荐

