您的位置:首页 > 其它

南阳oj 郁闷的c小加(二) 题目267

2015-08-01 17:28 232 查看

#include<stdio.h>

#include<stack>

#include<string.h>

#define N 1000

#include<stdlib.h>

using namespace std;

stack<char> str;//字符栈 转化为后缀式

stack<double> num;//数字栈 计算值

char s1
,s2
,s3[1000000];

int top;

int com(char x)//比较优先级

{

switch(x)

{

case '+':

case '-':return 1;

case '*':

case '/':return 2;

default:return -1;

}

}

void zhuan()//转化后缀式

{

scanf("%s",s1);//输入字符串

int k=strlen(s1);//获取长度

top=-1;//初始化头

str.push('#');//进入一个字符以防访问过界

for(int i=0;i<k;i++)

{

if(s1[i]>='0'&&s1[i]<='9'||s1[i]=='.')//数字就进入

{

top++;

s2[top]=s1[i];

}

else if(s1[i]=='+'||s1[i]=='-'||s1[i]=='*'||s1[i]=='/')

{

top++;

s2[top]=' ';

if(com(s1[i])>com(str.top())) str.push(s1[i]);//比较优先级,如果大就进入栈

else//否则就输出

{

while(com(str.top())>=com(s1[i]))

{

top++;

s2[top]=str.top();

top++;

s2[top]=' ';

str.pop();

}

str.push(s1[i]);

}

}

else if(s1[i]=='(') str.push(s1[i]);

else if(s1[i]==')')

{

while(str.top()!='(')

{

top++;

s2[top]=' ';

top++;

s2[top]=str.top();

str.pop();

}

str.pop();//删除左括号

}

}

while(str.top()!='#')//将剩余的全部输出

{

top++;

s2[top]=' ';

top++;

s2[top]=str.top();

str.pop();

}

for(int i=0;i<=top;i++)

{

if(s2[i]!=' ') printf("%c",s2[i]);

}

printf("=\n");

}

void ji()

{

while(!num.empty())

num.pop();

double a1,a2;

char x;

int k,t=-1;

for(int i=0;i<=top;i++)

{

k=0;

x=s2[i];

while(s1[i]!=' ')

{

if(s2[i]==' ') break;

s3[k]=s2[i];

k++;

i++;

}

if(x>='0'&&x<='9')

{

s3[k]='\0';

t++;

num.push(atof(s3));

}

else

{

switch(x)

{

case '+':

a1=num.top();

num.pop();

a2=num.top();

num.pop();

num.push(a1+a2);

break;

case '-':

a1=num.top();

num.pop();

a2=num.top();

num.pop();

num.push(a2-a1);

break;

case '*':

a1=num.top();

num.pop();

a2=num.top();

num.pop();

num.push(a2*a1);

break;

case '/':

a1=num.top();

num.pop();

a2=num.top();

num.pop();

num.push(a2/a1);

break;

}

}

}

printf("%.2lf\n\n",num.top());

}

int main()

{

int t;

scanf("%d",&t);

while(t--)

{

zhuan();

ji();

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: