【发布时间】:2015-11-05 17:52:45
【问题描述】:
1 #include<iostream>
2 using namespace std;
3
4 int main()
5 {
6 const double yen_to_euro=0.007215;
7 const double euro_to_dollar=1.12;
8 char currency;
9 double x;
10
11 while(currency!='q')
12 {
13 cout << "enter currency and unit(y , e, or d)";
14 cin >> x >>currency;
15
16 switch(currency){
17
18 case 'y':
19 cout <<"euro:"<< x*yen_to_euro<<" dollar:"<<x*yen_to_euro*euro_to_dollar<<'\n';
20 break;
21 case 'e':
22 cout <<"yen:"<< (x*(1.0/yen_to_euro))<<" dollar:"<<(x*euro_to_dollar)<<'\n';
23 break;
24 case 'd':
25 cout <<" yen:"<< x*(1.0/yen_to_euro)*(1.0/euro_to_dollar)<<" euro:"<<x*(1.0/euro_to_dollar)<<'\n';
26 break;
27 case 'q':
28 currency='q';
29 break;
30 default:
31 cout << "invalid";
32 break;
33
34 }
35
36 }
37
38
39 }
~
上述代码的预期功能是将选定的货币(y 代表日元,e 代表欧元,d 代表美元)转换为其他货币。
例如,如果我想兑换成 12 日元,我会输入:
12 年
然后程序会输出
欧元:0.08658 美元:0.0969696
但是,如果我输入 12e,我会收到一个无限循环。仔细检查代码,似乎没有任何逻辑错误。 尽管如此,我感觉问题的根源与第 14 行的 cin 有关,因为如果我像这样分别取 x 和货币类型:
cin>> x;
cin>> currency;
代码工作正常,但我需要输入金额,然后按回车,然后按代表货币类型的字符。有没有办法只在一行中输入所有内容,没有空格?
此外,它为什么会这样?这种通过无限循环的不寻常行为仅在我输入 e 表示 Euro 和 q 表示退出时发生。
【问题讨论】:
-
'e'字符使解析器误以为您正在尝试以科学计数法传递值。在大多数情况下,解析器会在遇到非数字字符时立即放弃,并返回它目前已解析的值。但在这种情况下,它会将'e'作为数字的一部分读取,切换到科学模式,然后确定数字格式错误并失败(您可以检查cin.good()以检查此错误和其他解析错误)。