我正在創建一個簡單的CLI計算器工具作爲練習。我需要確保n1和n2是數字才能使這些功能正常工作;因此,我希望在遇到預定的非數字值時使程序退出。驗證數字用戶輸入
任何人都可以給我一些方向嗎?
此外,如果任何人可以提供任何一般的提示,如何我可以做得更好,我將不勝感激。我只是在學習C++。
謝謝!
完整的代碼包含在下面。
#include <iostream>
#include <new>
using namespace std;
double factorial(double n) { return(n <= 1) ? 1 : n * factorial(n - 1); }
double add(double n1, double n2) { return(n1 + n2); }
double subtract(double n1, double n2) { return(n1 - n2); }
double multiply(double n1, double n2) { return(n1 * n2); }
double divide(double n1, double n2) { return(n1/n2); }
int modulo(int n1, int n2) { return(n1 % n2); }
double power(double n1, double n2) {
double n = n1;
for(int i = 1 ; i < n2 ; i++) {
n *= n1;
}
return(n);
}
void print_problem(double n1, double n2, char operatr) {
cout<<n1<<flush;
if(operatr != '!') {
cout<<" "<<operatr<<" "<<n2<<flush;
} else {
cout<<operatr<<flush;
}
cout<<" = "<<flush;
}
int main(void) {
double* n1, * n2, * result = NULL;
char* operatr = NULL;
n1 = new (nothrow) double;
n2 = new (nothrow) double;
result = new (nothrow) double;
operatr = new (nothrow) char;
if(n1 == NULL || n2 == NULL || operatr == NULL || result == NULL) {
cerr<<"\nMemory allocation failure.\n"<<endl;
} else {
cout<<"\nTo use this calculator, type an expression\n\tex: 3*7 or 7! or \nThen press the return key.\nAvailable operations: (+, -, *, /, %, ^, !)\n"<<endl;
do {
cout<<"calculator>> "<<flush;
cin>>*n1;
cin>>*operatr;
if(*operatr == '!') {
print_problem(*n1, *n2, *operatr);
cout<<factorial(*n1)<<endl;
} else {
cin>>*n2;
switch(*operatr) {
case '+':
print_problem(*n1, *n2, *operatr);
cout<<add(*n1, *n2)<<endl;
break;
case '-':
print_problem(*n1, *n2, *operatr);
cout<<subtract(*n1, *n2)<<endl;
break;
case '*':
print_problem(*n1, *n2, *operatr);
cout<<multiply(*n1, *n2)<<endl;
break;
case '/':
if(*n2 > 0) {
print_problem(*n1, *n2, *operatr);
cout<<divide(*n1, *n2)<<endl;
} else {
print_problem(*n1, *n2, *operatr);
cout<<" cannot be computed."<<endl;
}
break;
case '%':
if(*n1 >= 0 && *n2 >= 1) {
print_problem(*n1, *n2, *operatr);
cout<<modulo(*n1, *n2)<<endl;
} else {
print_problem(*n1, *n2, *operatr);
cout<<" cannot be computed."<<endl;
}
break;
case '^':
print_problem(*n1, *n2, *operatr);
cout<<power(*n1, *n2)<<endl;
break;
default:
cout<<"Invalid Operator"<<endl;
}
}
} while(true);
delete n1, n2, operatr, result;
}
return(0);
}
是否有一個原因是您正在創建變量而不是僅僅將它們放在堆棧上?你的代碼不再安全;它屈服於例外,並且更難以閱讀。 – GManNickG 2010-02-06 01:51:28
相關問題:http://stackoverflow.com/questions/2156467/how-can-i-check-if-a-number-double-type-stored-as-a-string-is-a-valid-double- nu/2156534#2156534 – Manuel 2010-02-06 06:47:05