表達式求值(一)

表達式求值

時間限制:3000 ms  |  內存限制:65535 KB
難度:3
描述

Dr.Kong設計的機器人卡多掌握了加減法運算以後,最近又學會了一些簡單的函數求值,比如,它知道函數min(20,23)的值是20 ,add(10,98) 的值是108等等。經過訓練,Dr.Kong設計的機器人卡多甚至會計算一種嵌套的更復雜的表達式。

假設表達式可以簡單定義爲:

1. 一個正的十進制數 x 是一個表達式。

2. 如果 和  表達式,則 函數min(x,y )也是表達式,其值爲x,y 中的最小數。

3. 如果 和  表達式,則 函數max(x,y )也是表達式,其值爲x,y 中的最大數。

4.如果 和  表達式,則 函數add(x,y )也是表達式,其值爲x,y 之和。

例如, 表達式 max(add(1,2),7) 的值爲 7。

請你編寫程序,對於給定的一組表達式,幫助 Dr.Kong 算出正確答案,以便校對卡多計算的正誤

輸入
第一行: N 表示要計算的表達式個數 (1≤ N ≤ 10) 
接下來有N行, 每行是一個字符串,表示待求值的表達式
(表達式中不會有多餘的空格,每行不超過300個字符,表達式中出現的十進制數都不
超過1000。)
輸出
輸出有N行,每一行對應一個表達式的值。
樣例輸入
3
add(1,2) 
max(1,999) 
add(min(1,1000),add(100,99)) 
樣例輸出
3
999
200
 
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

#define M 10000

typedef struct data
{
	int digital[M];
	int top;
}Data;

typedef struct str
{
	char string[M];
	int top;
}Str;

void pop_data(Data *p, char s);
void pop_str(Str *p);

int main()
{
	int n, i, lens, j;
	char s[M], a[M];
	int d = 0;
	Data data;
	Str str;

	scanf("%d", &n);
	getchar();

	while(n--)
	{
		memset(s, '\0', M);
		memset(a, '\0', M);
		memset(str.string, '\0', M);
		memset(data.digital, -1, sizeof(data.digital));

		gets(s);
		lens = strlen(s);

		j = 0;
		str.top = 0;
		data.top = 0;

		for(i = 0; i < lens; i++)
		{
			if(s[i] == '(')//將"("前面的字符及")"壓入棧中
			{
				str.string[str.top++] = s[i - 1];
				str.string[str.top++] = s[i];
			}
			else if(isdigit(s[i]) || s[i] == '-')//如果是數字或者是負號,將其放入a數組中
			{
				a[j++] = s[i];
				if(i == lens - 1)//將最後一個數壓入棧中
					if(a[0] != '\0')
					{
						sscanf(a, "%d", &d);
						j = 0;
						memset(a, '\0', M);
						data.digital[data.top++] = d;
					}
			}
			else if(s[i] ==  ',')//當遇到","時,說明前面的數字讀完了,將其轉化爲double型的壓入棧中
			{
				if(a[0] != '\0')
				{
					sscanf(a, "%d", &d);
					j = 0;
					memset(a, '\0', M);
					data.digital[data.top++] = d;
				}
			}
			if(s[i] == ')')//當遇到")"時,說明前面的數字讀完了,將其轉化爲double型的壓入棧中,並開始彈棧
			{
				if(a[0] != '\0')
				{
					sscanf(a, "%d", &d);
					j = 0;
					memset(a, '\0', M);
					data.digital[data.top++] = d;
				}

				pop_str(&str);
				pop_data(&data, str.string[str.top - 1]);
				pop_str(&str);
			}
		}
		if(data.top == 1)
			printf("%d\n", data.digital[0]);
	}

	return 0;
}

void pop_data(Data *p, char s)
{
	switch(s)
	{
	case 'd': p->digital[p->top - 2] = p->digital[p->top - 2] + p->digital[p->top - 1]; break;
	case 'n': p->digital[p->top - 2] = p->digital[p->top - 2] < p->digital[p->top - 1] ? p->digital[p->top - 2] : p->digital[p->top - 1]; break;
	default : p->digital[p->top - 2] = p->digital[p->top - 2] > p->digital[p->top - 1] ? p->digital[p->top - 2] : p->digital[p->top - 1]; break;
	}
	 p->digital[p->top - 1] = -1;
	 p->top--;
}

void pop_str(Str *p)
{
	p->top--;
	p->string[p->top] = '\0';
}
        


發佈了39 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章