我在 Stroustrup 的 PPP 第 2 版中做了一个尝试这个练习,该程序应该接受一个值,后跟一个表示货币的后缀。这应该换算成美元。以下代码适用于“15y”或“5p”,但当我输入“6e”时,它会显示“未知货币”。
constexpr double yen_per_dollar = 124.34;
constexpr double euro_per_dollar = 0.91;
constexpr double pound_per_dollar = 0.64;
/*
The program accepts xy as its input where
x is the amount and y is its currency
it converts this to dollars.
*/
double amount = 0;
char currency = 0;
cout << "Please enter an amount to be converted to USD\n"
<< "followed by its currency (y for yen, e for euro, p for pound):\n";
cin >> amount >> currency;
if (currency == 'y') // yen
cout << amount << currency << " == "
<< amount/yen_per_dollar << " USD.\n";
else if (currency == 'e') // euro
cout << amount << currency << " == "
<< amount/euro_per_dollar << " USD.\n";
else if (currency == 'p') // pound
cout << amount << currency << " == "
<< amount/pound_per_dollar << " USD.\n";
else
cout << "Unknown currency.\n";
如果我改为输入“6 e”,它工作正常,但我不明白为什么其他人即使没有空格也能工作。
最佳答案
6e 可以解释为格式错误的 double 科学记数法 (6e == 6e0 == 6 * pow(10,0) == 6
),因此它被 cin >> amount
读取和 >> currency
读取空字符串。
尝试 cin >> std::fixed >> amount
(来自 <iomanip>
)只强制使用“正常”符号。如果这没有帮助(并且它可能不会在大多数编译器上) - 你将不得不阅读行(std::getline()
)并手动解析它(在第一个非数字/dit 上拆分或从末尾读取等)
关于c++ - 货币选择有效,除非用户选择欧元或 'e',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31746256/