80c51用计算器程序

    xiaoxiao2024-12-29  11

    //由于这原本是写给c51用的c程序,所以没有添加stdio等标准库 //并且考虑到51RAM有限,大部分变量用unsigned char以节省空间

    include “operation.h”

    char stack1[55], stack2[55]; int pt1=-1, pt2=-1;

    void push(char ch, unsigned short i) { if(i==1)stack1[++pt1]=ch; else if(i==2)stack2[++pt2]=ch; }

    char pop(unsigned short i) { if(i==1)return stack1[pt1–]; else return stack2[pt2–]; }

    char top(unsigned short i) { if(i==1)return stack1[pt1]; else return stack2[pt2]; }

    void RPExpression(char exp[]) { unsigned char i; unsigned char ch, temp; push(‘@’,1); for(i=0;exp[i]!=’\0’;i++) { ch=exp[i]; switch(ch) { case ‘(‘: push(’ ‘,2); push(ch,1); break; case ‘)’: push(’ ‘,2); while(top(1)!=’(‘) { temp=pop(1); push(temp,2); } pop(1);//弹出’(’ break; case ‘+’: case ‘-‘: push(’ ‘,2); while(top(1)==’*’||top(1)==’/’||top(1)==’+’||top(1)==’-‘) { temp=pop(1); push(temp,2); } push(ch,1); break; case ‘*’: case ‘/’: push(’ ‘,2); while(top(1)==’*’||top(1)==’/’) { temp=pop(1); push(temp,2); } push(ch,1); break; default: push(ch,2); break; } } while(pt1>0) { temp=pop(1); push(temp,2); } }

    float getPRExpvalue() { float stack3[40]; int pt3=-1;

    unsigned char i, j, dot=0, left, right, ch; float fir, sec, num, fra; //for(i=0;i&lt;40;i++)stack3[i]=0; for(i=0;stack2[i]!='\0';i++) { ch=stack2[i]; if(ch&gt;='0'&amp;&amp;ch&lt;='9') { left=i; right=80; fra=num=dot=0; for(j=i+1;;j++) { if(stack2[j]=='.'){dot=j; continue;} if(!(stack2[j]&gt;='0'&amp;&amp;stack2[j]&lt;='9')){right=j-1; i=j-1; break;} } if(right!=80) { if(dot==0) { for(j=left;j&lt;=right;j++)num=num*10+(stack2[j]-'0')*1.0; fra=0; } else { for(j=left;j<dot;j++)num=num*10+(stack2[j]-'0')*1.0; for(j="right;j">dot;j--)fra=(fra+(stack2[j]-'0')*1.0)/10.0; } stack3[++pt3]=num+fra; } } else if(ch=='+'||ch=='-'||ch=='*'||ch=='/') { fir=stack3[pt3--]; sec=stack3[pt3--]; switch(ch) { case '+': num=sec+fir; break; case '-': num=sec-fir; break; case '*': num=sec*fir; break; case '/': num=sec/fir; break; } stack3[++pt3]=num; } } return stack3[pt3];

    }

    void initialStack() { unsigned char i; for(i=0;i<55;i++)stack1[i]=stack2[i]=’\0’; pt1=pt2=-1; }

    以下是头文件

    ifndef __OPERATION_H

    define __OPERATION_H

    void initialStack();//初始化栈空间 void RPExpression(char exp[]);//转化为逆波兰表达式 float getPRExpvalue();//获取逆波兰表达式的值

    endif

    转载请注明原文地址: https://ju.6miu.com/read-1295107.html
    最新回复(0)