我的第一个独立的C ++程序。我怎样才能改善它?

时间:2017-04-02 19:00:44

标签: c++ calculator

我在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;
}

1 个答案:

答案 0 :(得分:0)

我身边的一些想法:

  • 已经指出适当的缩进很重要
  • imo函数/方法名称应该是动词,因此我不会将其大写,即。添加 - &gt;添加。
  • 只能选择1个操作,因此if-elseif-else块会更有意义,甚至更好的切换语句。
  • 你应该从if语句中提取用于向用户提供结果的行,并在return语句之前只写一次。应尽可能避免多次复制相同的代码。