支持多位數(shù),括號,四則運算,的計算器算法c++實現(xiàn)

#include<iostream>

#include<string>

#include<stack>

#include<stdio.h>

using namespace std;

//23+(34*45)/(5+6+7)

//2+3*5+6+7

int priority(char c)

{

if (c == ')')

{

return 4;

}

else if (c == '^')

{

return 3;

}

else if (c == '*' || c == '/' || c == '%')

{

return 2;

}

else if (c == '+' || c == '-')

{

return 1;

}

else if (c == '(')

{

return 0;

}

else

{

cout << "不符合要求的字符!" << endl;

return -1;

}

} //返回字符c的優(yōu)先級

bool isNumber(char c)

{

if (c >= '0'&& c <= '9')

{

return true;

}

else

{

return false;

}

}

bool isOperator(char c)

{

if (c == '+' || c == '-' || c == '*' || c == '/' || c == '%')

{

return true;

}

else

{

return false;

}

}

bool isBracket(char c)

{

if (c == '(' || c == ')')

{

return true;

}

else

{

return false;

}

}

double charToDouble(char c)

{

return (double)(c - '0');

}

double stringToDouble(string s)

{

return atof(s.c_str());

}

int stringToInt(string s)

{

return atoi(s.c_str());

}

char doubleToChar(double d)

{

return (char)(d + 48);

}

string doubleToString(double d)

{

return to_string(d);

}

double charBasicCalculate(char left, char op, char right)

{

if (isNumber(left) && isNumber(right))

{

if (op == '+')

{

return (charToDouble(left) + charToDouble(right));

}

else if (op == '-')

{

return (charToDouble(left) - charToDouble(right));

}

else if (op == '*')

{

return (charToDouble(left) * charToDouble(right));

}

else if (op == '/')

{

return (charToDouble(left) / charToDouble(right));

}

else if (op == '%')

{

return (left - '0') % (right - '0');

}

else

{

cout << "操作符錯誤!";

return -1;

}

}

else

{

cout << "錯誤運算參數(shù)";

return -1;

}

}//返回double 的基本計算函數(shù)

double doubleBasicCalculate(double left, char op, double right)

{

if (op == '+')

{

return left + right;

}

else if (op == '-')

{

return left - right;

}

else if (op == '*')

{

return left*right;

}

else if (op == '/')

{

return left / right;

}

else if (op == '%')

{

return (int)left % (int)right;

}

else

{

cout << "操作符錯誤!";

return -1;

}

}

double stringBasicCalculate(string left, char op, string right)

{

if (op == '+')

{

return (stringToDouble(left) + stringToDouble(right));

}

else if (op == '-')

{

return (stringToDouble(left) - stringToDouble(right));

}

else if (op == '*')

{

return (stringToDouble(left) * stringToDouble(right));

}

else if (op == '/')

{

return (stringToDouble(left) / stringToDouble(right));

}

else if (op == '%')

{

return (stringToInt(left)) % (stringToInt(right));

}

else

{

cout << "操作符錯誤!";

return -1;

}

}

bool isExpression(const char* expression)//判斷表達(dá)式是否合法

{

int i = 0;

int leftBracket=0;//記錄左括號個數(shù)

int rightBracket=0;//記錄右括號個數(shù)

while (expression[i] != '\0')

{

if (expression[i] == ' ')

{

cout << "不要輸入空格!";

return false;

}

if (i == 0 && !(isNumber(expression[i]) || isBracket(expression[i])))//第一個元素不是數(shù)字或者左括號

{

cout << "異常1";

return false;

}

if (!(isNumber(expression[i]) || isOperator(expression[i]) || isBracket(expression[i])))//其它符合要求的字符

{

cout << "異常2";

return false;

}

if (i != 0 && isOperator(expression[i - 1]) && (isOperator(expression[i]) || expression[i] == ')'))//操作符后還是操作符或右括號不合法

{

cout << "異常3";

return false;

}

if (i!=0 && expression[i-1] == '(' && !isNumber(expression[i]))//左括號右邊不是數(shù)字debug2(i-1誤寫i)

{

cout << "異常4";

return false;

}

else

{

if (expression[i] == '(')

leftBracket++;

if (expression[i] == ')')

rightBracket++;

}

i++;//debug1添加上i++;

}

if (leftBracket == rightBracket)

{

return true;//表達(dá)式合理

}

else

{

cout << "異常5";

return false;

}

}

string dealBasicChar(char c, int n)//c表示位上的字符,n表示位級別,234,中c=2時n=2,c=3時,n=1,c=4時,n=0每個字符拆成0-9內(nèi)

{

string temp;

temp.append(1,c);

for (int i = 0; i < n; i++)

{

temp.append("*(9+1)");

}

/*cout << "dealBasicChar" << temp << endl;*/

return temp;

}

string dealBasicString(string s)

{

string temp;

temp.append("(");

int size = s.size();

for (int i = 0;i

{

temp.append(dealBasicChar(s.at(i), size - i - 1));

if (i != size - 1)//不是最后,添加"+";

{

temp.append("+");

}

}

temp.append(")");

/*cout << "dealBasciString" << temp << endl;*/

return temp;

}

string dealExpression(const char* expression)//化為0-9以內(nèi)的表達(dá)式:23+12:(9+1+9+1+3)+(9+1+2)

{

string temp = expression;

string temp2;

string texpression;

int i=0;

while(i

{

if (i!=temp.size()-1 && isNumber(temp.at(i)) && isNumber(temp.at(i+1)))//探測是否是多位數(shù)//debug當(dāng)i=temp.size()-1時調(diào)用temp.at(i+1)發(fā)生越界,加上條件,i!=temp.size()-1,當(dāng)i=temp.size()-1時由&&的處理原則,前面不成立不會執(zhí)行后面條件.

{

/*cout << i<

int j;

for ( j = 0; isNumber(temp.at(i + j)); j++)

{

temp2.append(1,temp.at(i+j));//獲得多位數(shù)存儲在temp2中

}

texpression.append(dealBasicString(temp2));//轉(zhuǎn)化為標(biāo)準(zhǔn)表達(dá)式并加入texpression中。

temp2.clear();//debug1:temp2為歸零導(dǎo)致錯誤.

/*cout << texpression << endl;*/

i = i + j ;

}

else

{

texpression.append(1,temp.at(i));

i++;

}

}

/*cout << texpression<

return texpression;

}

double infixCalculate(const char* expression)//直接計算中綴表達(dá)式debug1括號括號優(yōu)先級設(shè)置出錯 OK

{

stack opStack;

stack nuStack;

for (int i = 0; expression[i] != '\0'; i++)

{

if (isNumber(expression[i]))

{

cout << "isNumber" << endl;

nuStack.push(string(1,expression[i]));//轉(zhuǎn)化為string

}

else if (isOperator(expression[i]))

{

cout << "isOperator" << endl;

if (opStack.empty())//棧為空直接將操作符壓入

{

cout << "empty()" << endl;

opStack.push(expression[i]);

}

else//區(qū)分優(yōu)先級

{

cout << "not empty()" << endl;

if (priority(opStack.top()) < priority(expression[i]))

{

cout << "priority" << endl;

opStack.push(expression[i]);

}

else

{

cout << "not priority" << endl;

char op=opStack.top();//stack.top返回頂端元素不刪除,stack.pop無返回值只刪除頂端元素

opStack.pop();

string left = nuStack.top();

nuStack.pop();

string right = nuStack.top();

nuStack.pop();

nuStack.push(doubleToString(stringBasicCalculate(left, op, right)));

opStack.push(expression[i]);

}

}

}

else if (expression[i] == '(')

{

cout << "左括號" << endl;

opStack.push(expression[i]);

}

else if (expression[i] == ')')

{

cout << "右括號" << endl;

while (1)

{

if (opStack.top() == '(')

{

opStack.pop();//彈出左括號結(jié)束

break;

}

else

{

char op = opStack.top();

opStack.pop();

string left = nuStack.top();

nuStack.pop();

string right = nuStack.top();

nuStack.pop();

nuStack.push(doubleToString(stringBasicCalculate(left, op, right)));

}

}

}

else

{

cout << "符號錯誤!" << endl;

}

}

while (1)//計算剩余操作符

{

if (opStack.empty())

{

break;

}

else

{

char op = opStack.top();

opStack.pop();

string left = nuStack.top();

nuStack.pop();

string right = nuStack.top();

nuStack.pop();

nuStack.push(doubleToString(stringBasicCalculate(left, op, right)));

}

}

return stringToDouble(nuStack.top());

}

double postfixCalculate(const char* expression)

{

stack nuStack;

for (int i = 0; expression[i] != '\0'; i++)

{

if (isNumber(expression[i]))

{

nuStack.push(string(1, expression[i]));

}

else if (isOperator(expression[i]))

{

char op = expression[i];

string left = nuStack.top();

nuStack.pop();

string right = nuStack.top();

nuStack.pop();

nuStack.push(doubleToString(stringBasicCalculate(left, op, right)));

}

else

{

cout << "符號錯誤!" << endl;

}

}

return stringToDouble(nuStack.top());

}

string infixTranPostfix(const char* expressionIn)

{

stack opStack;

string temp;

for (int i = 0; expressionIn[i] != '\0'; i++)

{

if (isNumber(expressionIn[i]))

{

temp.append(1, expressionIn[i]);

}

else if (isOperator(expressionIn[i]))

{

if (opStack.empty())

{

opStack.push(expressionIn[i]);

}

else

{

if (priority(opStack.top()) < priority(expressionIn[i]))

{

opStack.push(expressionIn[i]);

}

else

{

temp.append(1, opStack.top());

opStack.pop();

opStack.push(expressionIn[i]);

}

}

}

else if (expressionIn[i] == '(')

{

opStack.push(expressionIn[i]);

}

else if (expressionIn[i] == ')')

{

while (1)

{

if (opStack.top() == '(')

{

opStack.pop();

break;

}

else

{

temp.append(1, opStack.top());

opStack.pop();

}

}

}

else

{

cout << "符號錯誤!";

}

}

while (1)

{

if (opStack.empty())

{

break;

}

else

{

temp.append(1, opStack.top());

opStack.pop();

}

}

return temp;

}

double calculate1(const char* expression)

{

if (isExpression(expression))

{

string tExpression = dealExpression(expression);

string ttExpression = infixTranPostfix(tExpression.c_str());

return postfixCalculate(ttExpression.c_str());

}

else

{

cout << "表達(dá)式錯誤!" << endl;

}

}

double calculate2(const char* expression)

{

if (isExpression(expression))

{

string s = dealExpression(expression);

return infixCalculate(s.c_str());

}

else

{

cout << "表達(dá)式錯誤!" << endl;

}

}

int main()

{

cout << "輸入一個表達(dá)式:" << endl;

string expression;

cin >> expression;

cout << "計算結(jié)果為:" << endl;

cout << calculate2(expression.c_str())<

/*cout << "請輸入表達(dá)式:" << endl;

string expression;

cin >> expression;

cout << "計算結(jié)果為:" << endl;

cout << calculate(expression.c_str())<

/*cout << "測試6:postfixCalculate" << endl; OK

string s1 = "1+2+2*3+4+(1+2*3)";

cout << infixTranPostfix(s1.c_str());*/

//5 測試 infixCalculate OK

//4 測試deal expression() Ok

/*string expression;

cin >> expression;

cout << dealExpression(expression);*/

/*char* expression;

double result;

cout << "輸入表達(dá)式:" << endl;

cin >> expression;*/

//1 測試isNumber(),isOperator(),isBracket() ?OK

//char c;

//cin >> c;

//if (isNumber(c))

//cout << "數(shù)字";

//else if (isOperator(c))

//cout << "操作符";

//else if (isBracket(c))

//cout << "括號";

//else

//cout << "其它字符";

//2 測試isExpression() ?OK

//char expression[100];

//cin >> expression;

//if (isExpression(expression))

//cout << "是表達(dá)式" << endl;

//else

//cout << "不是表達(dá)式" << endl;

//3 測試basicCalculat() ? OK

/*cout << basicCalculate('3', '%', '5');*/

/*int a = toascii('s');

int b = 's' - '0'+48;

cout << a << endl << b << endl;*/

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容