2013-01-31 89 views
-1

我如何編寫一個小型計算器,將四個算術運算中的一個作爲輸入,將這兩個參數作爲這些運算的輸入,然後輸出結果? 就這麼簡單,我不需要一個真正的計算器。如何用C++語言編寫一個小型計算器?

這裏是我試過到目前爲止,但遠沒有奏效:

#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 
    int x,y,result; 
    string arithmatic; 
    cout<<"enter the first number:"; 
    cin>>x; 
    cout<<"enter the second number:"; 
    cin>>y; 
    cout<<"use one of the four artimatic operations /, *, + or - :"; 
    cin>>arithmatic; 
    if (arithmatic=="/") 
    result=x/y; 
    cout<<"x/y ="<<result; 
    if (arithmatic == "*") 
    result=x*y; 
    cout<<"x * y ="<<result; 
    if (arithmatic == "+") 
    result = x + y; 
    cout<<"x+y ="<<result; 
    if (arithmatic == "-") 
    result = x-y; 
    cout<<"x-y ="<<result; 
    else 
    cout<<"what is this? i said use arithmatic operations!"; 

    return 0; 
} 

我知道有很多不對的節目,我剛開始學習的,這種做法是在一個書。

+3

顯示您迄今爲止編寫的代碼。 –

+0

你想學習如何編寫一個執行'+, - ,*,/'的小型計算器,但你不想要一個真正的計算器...抱歉...只是說... – czchlong

+1

打開文本編輯器並開始編碼... – Jason

回答

1

幾個問題:

  • 你錯過了很多括號你if語句之間。這導致在整個代碼中多次調用std::cout
  • 您正在使用很多由單個else終止的if語句,而是使用ifelse ifelse代替。
  • 您正在使用整數除法而不是浮點除法。如果你想要一個「準確」的結果,使用浮動代替。
2

如果這是請求的操作,您總是將結果寫入控制檯。

if (arithmatic =="/") 
    result=x/y; 
cout<<"x/y ="<<result; 
if (arithmatic == "*") 
    result=x*y; 
cout<<"x * y ="<<result; 
... 

它應該是:

if (arithmatic =="/") { 
    result=x/y; 
    cout<<"x/y ="<<result; 
} 
if (arithmatic == "*") { 
    result=x*y; 
    cout<<"x * y ="<<result; 
} 
... 

此外,由於情況是排他的,你倒是應該連續的塊,用else if。另一種選擇是使用switch (...) { case ... },但它可以像單個字符一樣對整數值進行操作。以字符串的第一個字符來應用此方法:

switch (arithmatic.at(0)) { 
    case '/': 
     result = x/y; 
     break; 
    case '*': 
     result = x * y; 
     break; 
    case '+': 
     result = x + y; 
     break; 
    case '-': 
     result = x - y; 
     break; 
    default: 
     cout << "what is this? i said use arithmatic operations!" << endl; 
     exit(1); // abort execution 
} 
cout << "x " << arithmatic << " y = " << result << endl; 

另外,您應該考慮您目前只使用整數。不僅輸入不能是任何小數,而且你還在做整數除法,即使必須舍入整數(在這種情況下向下舍入),結果也爲整數。要解決此問題,請使用double類型(而不是int)作爲操作數,以獲得較高的準確性(使用double時可能會有大約17個有意義的小數位數)。

請注意,您拼寫的算術錯誤。我在上面的代碼中使用了錯誤的拼寫。

1

else只是懸在最後。它必須符合if聲明。通常寫這種東西的方法是

if (first) 
    do_first(); 
else if (second) 
    do_second(); 
else if (third) 
    do_third(); 
else 
    do_everything_else(); 

現在你的練習就是將這個結構和@leemes給你看的大括號結合起來。