【NYOJ-35】表达式求值——简单栈练习

时间:2023-03-09 17:49:08
【NYOJ-35】表达式求值——简单栈练习

表达式求值

时间限制:3000 ms  |  内存限制:65535 KB
难度:3
描述

Dr.Kong设计的机器人卡多掌握了加减法运算以后,最近又学会了一些简单的函数求值,比如,它知道函数min(20,23)的值是20 ,add(10,98) 的值是108等等。经过训练,Dr.Kong设计的机器人卡多甚至会计算一种嵌套的更复杂的表达式。

假设表达式可以简单定义为:

1. 一个正的十进制数 x 是一个表达式。

2. 如果 x 和 y 是 表达式,则 函数min(x,y )也是表达式,其值为x,y 中的最小数。

3. 如果 x 和 y 是 表达式,则 函数max(x,y )也是表达式,其值为x,y 中的最大数。

4.如果 x 和 y 是 表达式,则 函数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<iostream>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<stack>
using namespace std; stack<int> s; int min(int p,int q){
// if(p > q) return q;
// else return p;
return p >= q ? q : p;
} int max(int p,int q){
// if(p > q) return p;
// else return q;
return p >= q ? p : q;
} int add(int p,int q){
return p+q;
} void reverse(char a[]){
char b[];
memset(b,,sizeof(b));
strcpy(b,a);
for(int i = ;i < strlen(a);i++)
a[i] = b[strlen(b)-i-];
}
int main(){
int n;
char a[],str[];
scanf("%d",&n);
getchar();
while(n--){
int k = ,ex = ;
gets(a);
memset(str,,sizeof(str));
if(a[strlen(a)-] != ')'){
printf("%s\n",a);
continue;
}
for(int i = strlen(a) - ; i >= ;i--){
if(a[i] == ')') continue;
if(a[i] != ',' && a[i] != '(') str[k++] = a[i];
if(a[i-] == ',' || a[i-] == '('){
reverse(str);
ex = atof(str);
k = ;
memset(str,,sizeof(str));
s.push(ex);
}
if(a[i] == '('){
int p,q; //获得栈中数据
p = s.top(); s.pop();
q = s.top(); s.pop();
switch(a[i-]){
case 'd': s.push(add(p,q)); i-=; continue;
case 'n': s.push(min(p,q)); i-=; continue;
case 'x': s.push(max(p,q)); i-=; continue;
}
}
}
printf("%d\n",s.top());
}
return ;
}

【总结】

  字符串转为双精度数值:

 //语法:
#include <stdlib.h>
double atof( const char *str );
//功能:将字符串str转换成一个双精度数值并返回结果。参数str必须以有效数字开头,但是允许以“E”或“e”除外的任意非数字字符结尾。例如:
//x = atof( "42.0is_the_answer" );
//x的值为42.0.

  const:

    关键字const用来告诉编译器一个一旦被初始化过的变量就不能再修改

    const int a=5; 与 int const a=5; 等同

    类名 const 对象名 与 const 类名 对象名 等同