最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C++實(shí)現(xiàn)簡(jiǎn)單計(jì)算器功能

 更新時(shí)間:2020年05月18日 10:04:36   作者:我來(lái)試試  
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)簡(jiǎn)單計(jì)算器功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

C++實(shí)現(xiàn)簡(jiǎn)單計(jì)算器的具體代碼,供大家參考,具體內(nèi)容如下

要求:輸入一個(gè)包含+ - * /的非負(fù)整數(shù)計(jì)算表達(dá)式,計(jì)算表達(dá)式的值,每個(gè)字符之間需有一個(gè)空格,若一行輸入為0,則退出程序。

輸入樣例:

4 + 2 * 5 - 7 / 11

輸出樣例:

13.36

實(shí)現(xiàn)代碼:

#include <iostream>
#include <stack> 
using namespace std;
char str[200];//保存表達(dá)式字符串 
int mat[][5]={//設(shè)置優(yōu)先級(jí)1表示優(yōu)先級(jí)較大,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;//運(yùn)算符棧 
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;
}

測(cè)試輸出:

2 + 4 * 2 - 2
8.00

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

台州市| 巨鹿县| 长汀县| 麻栗坡县| 郸城县| 巢湖市| 阆中市| 长顺县| 泰来县| 墨竹工卡县| 阿克陶县| 塘沽区| 五莲县| 新平| 台东市| 离岛区| 蕲春县| 图木舒克市| 漯河市| 湾仔区| 弋阳县| 千阳县| 明水县| 绥江县| 游戏| 洞头县| 尉犁县| 宝山区| 锦屏县| 邹城市| 天全县| 德州市| 黑水县| 晋城| 睢宁县| 崇左市| 广河县| 贵德县| 普兰店市| 赣州市| 安远县|