2017-04-02 49 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语句中提取用于向用户显示结果的行,并且在返回语句之前只写入一次。尽可能避免多次复制相同的代码。
相关问题