C - Write the program expr which evaluates a reverse Polish expression from the command line

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程

/*
 * Write the program expr, which evaluates a reverse Polish expression from the
 * command line, where each operator or operand is a separate argument. For example,
 * expr 2 3 4 + *
 * evaluates 2 * (3+4).
 *
 * Expr.c - by FreeMan
 */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

#define NUMBER 0

void push(double f);
double pop(void);

main(int argc, char *argv[])
{
	int type;
	int c;
	double op1, op2, latest;
	while (--argc > 0)
	{
		*++argv;
		if (!isdigit(c = **argv) && strlen(*argv) == 1)
		{
			type = c;
		}
		else
		{
			type = NUMBER;
		}
		switch (type)
		{
		case NUMBER:
			push(atof(*argv));
			break;
		case '+':
			push(pop() + pop());
			break;
		case '*':
			push(pop() * pop());
			break;
		case '-':
			op2 = pop();
			push(pop() - op2);
			break;
		case '/':
			op2 = pop();
			if (op2 != 0.0)
			{
				push(pop() / op2);
			}
			else
			{
				printf("error: zero divisor\n");
			}
			break;
		case '%':
			op2 = pop();
			if (op2 != 0.0)
			{
				push(fmod(pop(), op2));
			}
			else
			{
				printf("error: zero divisor\n");
			}
			break;
		case '^':
			op2 = pop();
			op1 = pop();
			if (op1 == 0.0 && op2 <= 0)
			{
				printf("if x = 0.0, y must be greater than 0\n");
			}
			else
			{
				push(pow(op1, op2));
			}
			break;
		case 'e':
			push(exp(pop()));
			break;
		case '~':
			push(sin(pop()));
			break;
		default:
			printf("error: unknown command: %c\n", type);
			break;
		}
	}
	latest = pop();
	printf("\t%.8g\n", latest);
	return 0;
}

#define MAXVAL 100

int sp = 0;
double val[MAXVAL];

/* push: push f onto value stack */
void push(double f)
{
	if (sp < MAXVAL)
		val[sp++] = f;
	else
		printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
	if (sp > 0)
		return val[--sp];
	else {
		printf("error: stack empty\n");
		return 0.0;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值