【发布时间】:2015-05-30 22:08:37
【问题描述】:
作为课程的一部分,我用 C++ 编写了一个简单的程序来在货币之间进行转换。它要求输入一个数值,然后是一个字母(y、e 或 p)来表示一种受支持的货币。使用 'y' 或 'p' 时,您可以将数值和字符一起输入或用空格分隔(即:“100y”或“100 y”),它会正常工作。但是,仅对于字母“e”,如果我同时输入两者,它不会被识别为有效输入。有人知道为什么吗?
代码如下:
#include <iostream>
int main()
{
using namespace std;
constexpr double yen_to_dollar = 0.0081; // number of yens in a dollar
constexpr double euro_to_dollar = 1.09; // number of euros in a dollar
constexpr double pound_to_dollar = 1.54; // number of pounds in a dollar
double money = 0; // amount of money on target currency
char currency = 0;
cout << "Please enter a quantity followed by a currency (y, e or p): " << endl;
cin >> money >> currency;
if(currency == 'y')
cout << money << "yen == " << yen_to_dollar*money << "dollars." << endl;
else if(currency == 'e')
cout << money << "euros == " << money*euro_to_dollar << "dollars." << endl;
else if(currency == 'p')
cout << money << "pounds == " << money*pound_to_dollar << "dollars." << endl;
else
cout << "Sorry, currency " << currency << " not supported." << endl;
return 0;
}
【问题讨论】:
-
原因是
100y不是有效数字的开头,而100e是科学计数法的-。 -
不要使用浮点数作为货币。人们会因为零钱而感到好笑
标签: c++ if-statement comparison