2017-04-02 20 views
-2

只是一個簡單的計算器,我是用C++編寫的第一個編碼,我很樂意接受有關如何改進的建設性批評!
我只使用整數的操作,希望現在就簡化它!我的第一個獨立的C++程序。我該如何改進它?

#include <iostream> 
using namespace std; 

//Simple calculator that handles +,-,*,/ with whole numbers 


int Add (int x, int y){ 
return (x+y); 
} 
int Sub (int x, int y){ 
return (x-y); 
} 
int Mult (int x, int y){ 
return (x*y); 
} 
int Div (int x, int y){ 
return (x/y); 
} 
int main(){ 
enum operation {sum, subtract, multiply, divide}; 
operation operationSelect; 
int sel; 
int a,b,c; 

cout << "Which 2 numbers do you want to perform an operation on?\n"; 
cin >> a; 
cin >> b; 
cout << "Which operation do you want to perform? sum, subtract, multiply, divide (0-3)\n"; 
cin >> sel; 
operationSelect = operation(sel); 


if (operationSelect == sum){ 
    c = Add (a, b); 
    cout << "The result is: " << c << endl; 
} 

if (operationSelect == subtract){ 
    c = Sub (a, b); 
    cout << "The result is: " << c << endl; 
} 

if (operationSelect == multiply){ 
    c = Mult (a, b); 
    cout << "The result is: " << c << endl; 
} 

if (operationSelect == divide){ 
    c = Div (a, b); 
    cout << "The result is: " << c << endl; 
} 

return 0; 
} 
+2

通過縮進代碼來改進它。 –

+1

codereview.stackexchange.com將是一個更好的地方發佈此 – JVApen

+0

不用於stackoverflows格式,對於可憐的縮進感到抱歉! – vuskovic09

回答

0

只是一對夫婦的從我身邊的想法:

  • 如已經指出正確的縮進是重要
  • IMO函數/方法名是一個動詞,所以我不會利用它即。添加 - >添加。
  • 它只能選擇恰好1個操作,所以if-elseif-else塊會更有意義,或者甚至更好的是switch語句。
  • 您應該從if語句中提取用於向用戶顯示結果的行,並且在返回語句之前只寫入一次。儘可能避免多次複製相同的代碼。
相關問題