C++實(shí)現(xiàn)簡單計(jì)算器功能
C++實(shí)現(xià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;
}
測試輸出:
2 + 4 * 2 - 2
8.00
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C++ STL vector的模擬實(shí)現(xiàn)
這篇文章主要介紹了C++ STL vector的模擬實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
使用用C++做一顆會(huì)跳動(dòng)的愛心實(shí)例代碼
大家好,本篇文章主要講的是使用用C++做一顆會(huì)跳動(dòng)的愛心實(shí)例代碼,感興趣的同學(xué)趕快來看一看吧,歡迎借鑒學(xué)習(xí)C++做一顆會(huì)跳動(dòng)的愛心實(shí)例代碼2021-12-12
C語言循環(huán)鏈表實(shí)現(xiàn)貪吃蛇游戲
這篇文章主要為大家詳細(xì)介紹了C語言循環(huán)鏈表實(shí)現(xiàn)貪吃蛇,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-11-11
詳解Visual Studio 2019(VS2019) 基本操作
這篇文章主要介紹了詳解Visual Studio 2019(VS2019) 基本操作,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03

