栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

PTA Evaluate Postfix Expression (15 分)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PTA Evaluate Postfix Expression (15 分)

3-4 evaluate Postfix expression (15 分)

Write a program to evaluate a postfix expression. You only have to handle four kinds of operators: +, -, x, and /.

Format of functions:

ElementType evalPostfix( char *expr );

where expr points to a string that stores the postfix expression. It is guaranteed that there is exactly one space between any two operators or operands. The function evalPostfix is supposed to return the value of the expression. If it is not a legal postfix expression, evalPostfix must return a special value Infinity which is defined by the judge program.

Sample program of judge:

#include 
#include 

typedef double ElementType;
#define Infinity 1e8
#define Max_Expr 30   

ElementType evalPostfix( char *expr );

int main()
{
    ElementType v;
    char expr[Max_Expr];
    gets(expr);
    v = evalPostfix( expr );
    if ( v < Infinity )
        printf("%fn", v);
    else
        printf("ERRORn");
    return 0;
}


Sample Input 1:

11 -2 5.5 * + 23 7 / -
结尾无空行

Sample Output 1:

-3.285714
结尾无空行

Sample Input 2:

11 -2 5.5 * + 23 0 / -

Sample Output 2:

ERROR

Sample Input 3:

11 -2 5.5 * + 23 7 / - *

Sample Output 3:

ERROR

分析:
题目的意思是将给出的后缀表达式进行计算,返回结果
后缀表达式:遇到数字进栈,遇到运算符,出栈两个元素,进行运算,再进栈,需要注意的是,出栈的元素为A(先出),B(后出),运算为:B(±*/)A
是有先后顺序的
AC代码如下:

ElementType evalPostfix( char *expr ){
	int i,j,k,l,top=-1;
	l=strlen(expr);
	double sum[5000] = {0};
	for(i=0;i
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/588463.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号