蓝桥杯--算法训练 表达式计算
生活随笔
收集整理的這篇文章主要介紹了
蓝桥杯--算法训练 表达式计算
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:http://lx.lanqiao.cn/problem.page?gpid=T419
atof函數講解: 頭文件:#include <stdlib.h>
函數 atof() 用于將字符串轉換為雙精度浮點數(double),其原型為:
double atof (const char* str);
atof() 的名字來源于 ascii to floating point numbers 的縮寫,它會掃描參數str字符串,跳過前面的空白字符(例如空格,tab縮進等,可以通過 isspace() 函數來檢測),直到遇上數字或正負符號才開始做轉換,而再遇到非數字或字符串結束時('\0')才結束轉換,并將結果返回。參數str 字符串可包含正負號、小數點或E(e)來表示指數部分,如123. 456 或123e-2。
【返回值】返回轉換后的浮點數;如果字符串 str 不能被轉換為 double,那么返回 0.0。
思路:根據符號的優先級進行運算,本代碼實現為定義兩個運算函數
include<cstdio> #include<stack> #include<string> #include<cstring> #include<cmath> #include<ctype.h>using namespace std;stack <char> sCh; //用于存放符號的符號棧 stack <double> sNum;//用于存放數據的數據棧 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);//將新的結果入棧 sCh.pop();//刪除用過的符號 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('(');//現將最低優先級的左括號入棧 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函數讀取數字 注意這里的數字0存到數組里是字母‘a’可以理解為結束標志 if(num[0]!=0){n=atof(num);num[0]=0;sNum.push(n);}k=0; //下標歸零 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; }
總結
以上是生活随笔為你收集整理的蓝桥杯--算法训练 表达式计算的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 架构设计 | 高并发流量削峰,共享资源加
- 下一篇: 【蓝桥杯】算法提高 7-2求arccos