我的第一个独立的 C++ 程序。我该如何改进它?
My first independent C++ program. How can i improve it?
只是一个简单的计算器,是我用 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;
}
我的一些想法:
- 正如已经指出的那样,适当的缩进很重要
- imo function/method 名字应该是动词,因此我不会大写。添加 -> 添加。
- 只能 select 恰好 1 个操作,因此 if-elseif-else 块会更有意义,甚至更好的是 switch 语句。
- 你应该从 if 语句中提取出向用户显示结果的行,并且只在 return 语句之前写一次。尽可能避免多次复制相同的代码。
只是一个简单的计算器,是我用 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;
}
我的一些想法:
- 正如已经指出的那样,适当的缩进很重要
- imo function/method 名字应该是动词,因此我不会大写。添加 -> 添加。
- 只能 select 恰好 1 个操作,因此 if-elseif-else 块会更有意义,甚至更好的是 switch 语句。
- 你应该从 if 语句中提取出向用户显示结果的行,并且只在 return 语句之前写一次。尽可能避免多次复制相同的代码。