如有不对,不吝赐教
进入正题:
算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。前缀表达式指二元运算符位于两个运算数之前,例如2+3*(7-4)+8/4的前缀表达式是:+ + 2 * 3 - 7 4 / 8 4。请设计程序计算前缀表达式的结果值。
输入格式:
输入在一行内给出不超过30个字符的前缀表达式,只包含+、-、*、/以及运算数,不同对象(运算数、运算符号)之间以空格分隔。
输出格式:
输出前缀表达式的运算结果,保留小数点后1位,或错误信息ERROR。
输入样例:
+.+ 2 * 3 - 7 4 / 8 4
输出样例:
13.0
这道题目由中缀表达式求前缀表达式,我们只要构造一棵前缀树,然后在利用前缀树进行计算就可以了,需要注意的就是数字的处理,有非个位数的数字以及可能有负数。
下面给代码:
#include<stdio.h>
#include<malloc.h>
int flag; //表示是否有错误
struct SuffixTree{
int flag; //该节点是否为数字节点
char sign;
double number;
struct SuffixTree *left,*right;
}; //前缀树
double Atof(char *str);
struct SuffixTree *Insert(struct SuffixTree *root,double number,char sign);
double Cal(double num1,double num2,char sign);
void Free(struct SuffixTree *root);
int main(void)
{
int i,j;
char input[31];
char number[31];
double result;
struct SuffixTree *root;
root=(struct SuffixTree *)malloc(sizeof(struct SuffixTree));
root->left=root->right=NULL;
root->flag=-1;
fgets(input,30,stdin);
for(i=0;'\n'!=input[i]&&input[i]&&!flag;){
if(' '==input[i]){
i++;
continue;