C++實現(xiàn)簡單計算器功能
更新時間:2020年05月18日 10:04:36 作者:我來試試
這篇文章主要為大家詳細介紹了C++實現(xiàn)簡單計算器功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
C++實現(xiàn)簡單計算器的具體代碼,供大家參考,具體內(nèi)容如下
要求:輸入一個包含+ - * /的非負整數(shù)計算表達式,計算表達式的值,每個字符之間需有一個空格,若一行輸入為0,則退出程序。
輸入樣例:
4 + 2 * 5 - 7 / 11
輸出樣例:
13.36
實現(xiàn)代碼:
#include <iostream> #include <stack> using namespace std; char str[200];//保存表達式字符串 int mat[][5]={//設置優(yōu)先級1表示優(yōu)先級較大,0表示較小 1,0,0,0,0, 1,0,0,0,0, 1,0,0,0,0, 1,1,1,0,0, 1,1,1,0,0, }; stack<int> op;//運算符棧 stack<double> in;//數(shù)字棧 void getOp(bool &reto,int &retn,int &i){ if(i==0&&op.empty()==true){ reto=true; retn=0; return; } if(str[i]==0){ reto=true; retn=0; return; } if(str[i]>='0'&&str[i]<='9'){ reto=false; }else{ reto=true; if(str[i]=='+'){ retn=1; }else if(str[i]=='-'){ retn=2; }else if(str[i]=='*'){ retn=3; } else if(str[i]=='/'){ retn=4; } i+=2; return; } retn=0; for(;str[i]!=' '&&str[i]!=0;i++){ retn*=10; retn+=str[i]-'0'; } if(str[i]==' '){ i++; } return; } int main(int argc, char *argv[]) { while(gets(str)){ if(str[0]=='0'&&str[1]==0) break; bool retop;int retnum; int idx=0; while(!op.empty()) op.pop(); while(!in.empty()) in.pop(); while(true){ getOp(retop,retnum,idx); if(retop==false){ in.push((double)retnum); } else { double tmp; if(op.empty()==true||mat[retnum][op.top()]==1){ op.push(retnum); } else{ while(mat[retnum][op.top()]==0){ int ret=op.top(); op.pop(); double b=in.top(); in.pop(); double a=in.top(); in.pop(); if(ret==1) tmp=a+b; else if(ret==2) tmp=a-b; else if(ret==3) tmp=a*b; else tmp=a/b; in.push(tmp); } op.push(retnum); } } if(op.size()==2&&op.top()==0) break; } printf("%.2f\n",in.top()); } return 0; }
測試輸出:
2 + 4 * 2 - 2
8.00
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Visual Studio 2019(VS2019) 基本操作
這篇文章主要介紹了詳解Visual Studio 2019(VS2019) 基本操作,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03