Cod sursa(job #724388)

Utilizator teodora.petrisorPetrisor Teodora teodora.petrisor Data 26 martie 2012 15:08:37
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
//============================================================================
// Name        : ExprEval.cpp
// Author      : Petrisor Teodora
// Version     :
// Copyright   : 
// Description : Hello World in C++, Ansi-style
//============================================================================

#include<fstream>
using namespace std;


const long int MAX = 100010;		// declare maximum size of string
char expr[MAX], *p = expr;		// reserve space for string and declare pointer to beginning of string

long term();					// declare needed functions
long factor();

/*
 * Adds all the terms of an expression
 */
long evaluate()
{
	long r = term();

	while(*p == '+' || *p == '-')
	{
		switch(*p)
		{
		case '+':
			++p;				// go over the plus sign
			r += term();		// add what follows
			break;
		case '-':
			++p;				// go over the minus sign
			r -= term();		// subtract what follows
			break;
		}
	}

	return r;
}


/*
 * Deals with the contents of a term, which is composed of multiplied/divided factors
 */
long term()
{
	long r = factor();
	while(*p == '*' || *p == '/')
	{
		switch(*p)
		{
		case '*':
			p ++;
			r *= factor();
			break;
		case '/':
			p++;
			r /= factor();
			break;
		}
	}

	return r;
}


/*
 * Returns the value of a factor, which can be either a subexpression OR a natural number
 */
long factor()
{
	long r = 0;

	if(*p == '(')				// if we have a subexpression
	{
		++p;					// go over bracket
		r = evaluate();			// evaluate subexpression
		++p;					// go over closing bracket
	}
	else
	{
		while( *p >= '0' && *p <= '9')		// if we have a number
		{
			r = r * 10 + *p - '0';			// obtain the value
			++p;
		}
	}

	return r;
}






int main()
{

	ofstream output("evaluare.out");

	fgets(expr, MAX, fopen("evaluare.in", "r"));

	output<<evaluate();

	output.close();

	return 0;

}