表达式求值
[cpp]描述:思路很简单,优先级比较完的情况下,采用两个栈就可以完成了……
[cpp]
#include <iostream>
#include <cstdio>
#include <cstring>
#include "hanshu.h" //头文件
using namespace std;
int flag;//下面会多次用到flag
int num_value(char *s,char *str,double *num,int len,int i,int j);//计算实数值存入num中
char get_precede(char a,char b);//比较两个字符优先级,获取优先级
int calculate_num(char c,double *num,int j);//优先级比较大小后计算结果
double solve_s(char *s ,char *str,double *num,int len);//处理函数,得出等式的结果
int main()
{
freopen("a.txt","r",stdin);
double num[10010];
char c,s[10010],str[10010];
memset(s,0,sizeof(s));
int left,right,len;
left=right=len=flag=0;
while(scanf("%c",&c)!=EOF)//单字符输入
{
if((c>='0'&&c<='9')||c=='.'||c=='('||c==')'||c=='+'||c=='-'||c=='*'||c=='/')//选择合适的字符输入
{
s[len++]=c;
if(c=='(')
{
if(!right)flag=1;
left++;
}
else if(c==')')
{
right++;
if(!left) flag=2;
}
}
if(c=='\n')//讨论几种不符合情况的输入
{
if(flag==2) printf("输入错误,首先出现了右括号!\n");
else if(left>right) printf("左括号比右括号多!\n");
else if(left<right) printf("右括号比左括号多!\n");
else if(len<=0) printf("没有数据!\n");
else
{
s[len++]='#';
flag=0;
memset(str,0,sizeof(str));
memset(num,0,sizeof(num));
double x=solve_s(s,str,num,len);
if(flag) printf("出现零为除数\n");
else printf("solve_s=%g\n",x);
}
memset(s,0,sizeof(s));
flag=len=left=right=0;
}
}
return 0;
}
[cpp]
//头文件
[cpp]
<pre name="code" class="cpp">#ifndef HANSHU_H_INCLUDED
#define HANSHU_H_INCLUDED
char str_operator[]= {'+','-','*','/','(',')','#'};
char str_precede[7][7]=
{
{'>','>','<','<','<','>','>'},
{'>','>','<','<','<','>','>'},
{'>','>','>','>','<','>','>'},
{'>','>','>','>','<','>','>'},
{'<','<','<','<','<','=',' '},
{'>','>','>','>',' ','>','>'},
{'<','<','<','<','<',' ','='}
};
extern int flag;
int num_value(char *s,char *str,double *num,int len,int i,int j)
{
int k,count(0),c(0);
for( k=i; k<len; k++)
if(s[k]>='0'&&s[k]<='9')
{
num[j]=num[j]*10+s[k]-'0';
if(c) count++;
}
else if(s[k]=='.') c=1;
else break;
for( c=0; c<count; c++)
num[j]/=10;
if((i==1&&(s[i-1]=='+'||s[i-1]=='-'))||(i>=2&&(s[i-1]=='-'||s[i-1]=='+')&&s[i-2]=='('))
{
flag=1;
if(s[i-1]=='-') num[j]=0-num[j];
}
return k;
}
char get_precede(char a,char b)
{
int i,j;
for(int k=0; k<7; k++)
{
if(a==str_operator[k]) i=k;
if(b==str_operator[k]) j=k;
&n
补充:软件开发 , C++ ,