我正在使用switch语句创建一个简单的货币转换程序,如下所示:
#include "library/std_lib_facilities.h"
int main()
{//This program converts yen, euros, yuan, kroner and pounds to dollars
double amount = 0;
char currency = ' ';
//one dollar equivalent of each currency
const double yen_to_dollar = 113.67;
const double pounds_to_dollar = 0.85;
const double euros_to_dollar = 0.95;
const double yuan_to_dollar = 6.87;
const double kroner_to_dollar = 7.04;
//case labels corresponding to currency
const char y = 'y', p = 'p', e = 'e', u = 'u', k = 'k';
cout << "Please type the amount you want to convert, followed by the currency(y,e,p,u,k) u is for yuan: ";
while(cin >> amount >> currency ) {
switch(currency) {
case y:
cout << amount << " yen == " << amount / yen_to_dollar << " dollars." << '\n';
break;
case p:
cout << amount << " pounds == " << amount / pounds_to_dollar << " dollars." <<'\n';
break;
case e:
cout << amount << " euros == " << amount / euros_to_dollar << " dollars." << '\n';
break;
case u:
cout << amount << " yuan == " << amount / yuan_to_dollar << " dollars." << '\n';
break;
case k:
cout << amount << " kroner == " << amount / kroner_to_dollar << " dollars." << '\n';
break;
default:
cout << "Please try supported currencies" << '\n';
break;
}
}
return 0;
}
我可以通过输入金额和货币来运行函数时将预定义的货币转换为美元,如下所示:5y(将5日元转换为等值的美元)。
除e
常数之外的每个其他数量和常量工作。代码在任何时候我想用一个数量和常数来测试它,例如(24E)。
当我将常量e = 'e'
更改为s = 's'
之类的内容时,它的效果非常好。
所以我的问题是为什么包含e字符的输入会破坏我的代码?
答案 0 :(得分:3)
这可能不是它,但输入的“23.4e”值是否被解释为指数?那是我的想法。您可以考虑解析它,先将字符串/ char部分删除到该部分的变量中。