2015-05-30 22 views
2

作爲課程的一部分,我已經用C++編寫了一個簡單的程序來在貨幣之間進行轉換。它要求一個數值,然後是一個字母(y,e或p)來表示其中一種支持的貨幣。當使用'y'或'p'時,您可以將數值和字符一起輸入或用空格分隔(例如:「100y」或「100y」),它可以正常工作。但是,僅字母'e',如果我輸入在一起,它不會識別爲有效的輸入。有誰知道爲什麼?在C++中的貨幣之間進行轉換的程序中的問題

下面的代碼:

#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; 
} 
+3

原因是'100y'不是有效數字的開始,而是'100e' - 以科學記數法。 – Angew

+0

請勿對貨幣使用浮點數。人們對奇幣 –

回答

2

當你進入100e10e它工作正常。 100e10是科學計數法中的有效數字。在科學計數法中,100e不是有效的數字。它不被轉換爲double,並且money被分配爲0.變量currency保持不變。這就是爲什麼你會得到「對不起,貨幣不支持」的消息。 e屬於這種情況下的一個數字,因爲它符合科學記數法格式。

您可以爲每種貨幣分配4個字符(例如_EUR)。它可以解決問題並且更加便於用戶使用。

+0

或者交換貨幣ID和價值感到有趣,例如, 'e100',無論如何它都是非常流行的符號,例如$ 5,£3 –

+0

當我輸入'100e'時,它給了我「對不起,貨幣不支持」的信息。 它不應該等待我輸入'貨幣'變量的值嗎? – Flip