C++怎么實現簡單計算器功能
小編這次要給大家分享的是C++怎么實現簡單計算器功能,文章內容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
成都創新互聯服務項目包括梅列網站建設、梅列網站制作、梅列網頁制作以及梅列網絡營銷策劃等。多年來,我們專注于互聯網行業,利用自身積累的技術優勢、行業經驗、深度合作伙伴關系等,向廣大中小型企業、政府機構等提供互聯網行業的解決方案,梅列網站推廣取得了明顯的社會效益與經濟效益。目前,我們服務的客戶以成都為中心已經輻射到梅列省份的部分城市,未來相信會繼續擴大服務區域并繼續獲得客戶的支持與信任!
要求:輸入一個包含+ - * /的非負整數計算表達式,計算表達式的值,每個字符之間需有一個空格,若一行輸入為0,則退出程序。
輸入樣例:
4 + 2 * 5 - 7 / 11
輸出樣例:
13.36
實現代碼:
#include#include using namespace std; char str[200];//保存表達式字符串 int mat[][5]={//設置優先級1表示優先級較大,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 op;//運算符棧 stack in;//數字棧 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
看完這篇關于C++怎么實現簡單計算器功能的文章,如果覺得文章內容寫得不錯的話,可以把它分享出去給更多人看到。
網頁名稱:C++怎么實現簡單計算器功能
文章URL:http://www.xueling.net.cn/article/jcesds.html