蓝桥杯--算法训练 表达式计算
生活随笔
收集整理的這篇文章主要介紹了
蓝桥杯--算法训练 表达式计算
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目鏈接:http://lx.lanqiao.cn/problem.page?gpid=T419
atof函數(shù)講解: 頭文件:#include <stdlib.h>
函數(shù) atof() 用于將字符串轉(zhuǎn)換為雙精度浮點(diǎn)數(shù)(double),其原型為:
double atof (const char* str);
atof() 的名字來源于 ascii to floating point numbers 的縮寫,它會(huì)掃描參數(shù)str字符串,跳過前面的空白字符(例如空格,tab縮進(jìn)等,可以通過 isspace() 函數(shù)來檢測(cè)),直到遇上數(shù)字或正負(fù)符號(hào)才開始做轉(zhuǎn)換,而再遇到非數(shù)字或字符串結(jié)束時(shí)('\0')才結(jié)束轉(zhuǎn)換,并將結(jié)果返回。參數(shù)str 字符串可包含正負(fù)號(hào)、小數(shù)點(diǎn)或E(e)來表示指數(shù)部分,如123. 456 或123e-2。
【返回值】返回轉(zhuǎn)換后的浮點(diǎn)數(shù);如果字符串 str 不能被轉(zhuǎn)換為 double,那么返回 0.0。
思路:根據(jù)符號(hào)的優(yōu)先級(jí)進(jìn)行運(yùn)算,本代碼實(shí)現(xiàn)為定義兩個(gè)運(yùn)算函數(shù)
include<cstdio> #include<stack> #include<string> #include<cstring> #include<cmath> #include<ctype.h>using namespace std;stack <char> sCh; //用于存放符號(hào)的符號(hào)棧 stack <double> sNum;//用于存放數(shù)據(jù)的數(shù)據(jù)棧 char num[105]; char str1[105];void cal_1()//接受加減乘除 {double n1,n2;char ch;ch=sCh.top();while(ch!='('){n1=sNum.top();sNum.pop();n2=sNum.top();sNum.pop();switch(ch){case '+': n2+=n1;break;case '-': n2-=n1;break;case '*': n2*=n1;break;case '/': n2/=n1;break;}sNum.push(n2);//將新的結(jié)果入棧 sCh.pop();//刪除用過的符號(hào) ch=sCh.top();} }void cal_2() {double n1,n2;char ch;ch=sCh.top();while(ch =='*' || ch =='/'){n1=sNum.top();sNum.pop();n2=sNum.top();sNum.pop();if(ch == '*'){n2*=n1;}else if(ch == '/'){n2/=n1;}sNum.push(n2);sCh.pop();ch=sCh.top();}} int main() {int k=0;double n;gets(str1);char c[2]="=";strcat(str1,c);sCh.push('(');//現(xiàn)將最低優(yōu)先級(jí)的左括號(hào)入棧 for(int i=0; str1[i]; ++i){if(str1[i]>='0' && str1[i]<='9' || str1[i]=='.'){num[k++]=str1[i];continue;}num[k]=0;//在尾部添加字母用于atof函數(shù)讀取數(shù)字 注意這里的數(shù)字0存到數(shù)組里是字母‘a(chǎn)’可以理解為結(jié)束標(biāo)志 if(num[0]!=0){n=atof(num);num[0]=0;sNum.push(n);}k=0; //下標(biāo)歸零 switch(str1[i]){case '+' :cal_1();sCh.push('+');break;case '-' :cal_1();sCh.push('-');break;case '*' :cal_2();sCh.push('*');break;case '/' :cal_2();sCh.push('/');break;case '(' :sCh.push(str1[i]);break;case ')' :cal_1();sCh.pop();break;case '=' :cal_1();sCh.pop();break;}}printf("%.0lf",sNum.top());return 0; }
總結(jié)
以上是生活随笔為你收集整理的蓝桥杯--算法训练 表达式计算的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 架构设计 | 高并发流量削峰,共享资源加
- 下一篇: SpringCloud微服务:Senti