前缀表达式文件读取计算
功能描述
自定义运算函数如:add(加),sub(减),mult(乘),div(除以),neg(取反),doubleMe(平方)计算嵌套函数调用式如:
add(20,sub(13,10))的值23。
运行示例
在文件中question.txt逐行存储:
add(23,45)
add(-20,sub(13,10))
add(sub(neg(4),12), muti(doubleMe(2),5))
div(54,add(3,sub(9,3))
将值写入文件answer.txt:
add(23,45)=68
add(20,sub(13,10)) = 23
add(sub(neg(4),12), muti(doubleMe(2),5)) = 4
div(54,add(3,sub(9,3)) = 6
#include <iostream>
#include <string>
#include <sstream>
#include <stack>
using namespace std;
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mult(int a, int b) { return a * b; }
int div(int a, int b) { return a / b; }
int neg(int a) { return -a; }
int doubleMe(int a) { return a * a; }
int evaluate(string exp) {
stringstream ss(exp);
string token;
stack<int> s;
while (ss >> token) {
if (token == "+" ) {
int b = s.top(); s.pop();
int a = s.top(); s.pop();
s.push(add(a, b));
} else if (token == "-") { ... /* similarly for other ops */ }
else {
s.push(stoi(token));
}
}
return s.top();
}
int main() {
string line;
ifstream infile("question.txt");
ofstream outfile("answer.txt");
while (getline(infile, line)) {
int result = evaluate(line);
outfile << line << "=" << result << endl;
}
return 0;
}
可以定义一个map,key是前缀字符串比如add,value是对应的add函数指针,就可以通过字符串的key调用对应的运算函数,对于括号的嵌套,可以用递归调用处理。
不知道你这个问题是否已经解决, 如果还没有解决的话:首先我们需要读取 question.txt 文件中的表达式,并逐行进行计算。我们可以使用Python的文件读取功能来实现。
接下来,我们需要编写一个函数来计算前缀表达式。我们可以使用递归的方法来解析和计算嵌套的表达式。
最后,我们需要将计算结果写入 answer.txt 文件中。
以下是解决该问题的代码实现:
# 定义运算函数
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mult(a, b):
return a * b
def div(a, b):
return a / b
def neg(a):
return -a
def doubleMe(a):
return a * a
# 递归计算前缀表达式
def calculate_expression(expression):
# 判断是否为数字,如果是则直接返回
if expression.isdigit():
return int(expression)
# 解析表达式
operator, operand1, operand2 = expression.split('(', 1)[1].strip(')').split(',', 1)
# 递归计算操作数
operand1 = calculate_expression(operand1)
operand2 = calculate_expression(operand2)
# 根据操作符计算结果
if operator == 'add':
return add(operand1, operand2)
elif operator == 'sub':
return sub(operand1, operand2)
elif operator == 'mult':
return mult(operand1, operand2)
elif operator == 'div':
return div(operand1, operand2)
elif operator == 'neg':
return neg(operand1)
elif operator == 'doubleMe':
return doubleMe(operand1)
else:
raise ValueError("Unsupported operator: {}".format(operator))
# 读取 question.txt 文件并计算表达式
with open('question.txt', 'r') as question_file:
expressions = question_file.readlines()
# 计算结果并写入 answer.txt 文件
with open('answer.txt', 'w') as answer_file:
for expression in expressions:
result = calculate_expression(expression.strip())
answer_file.write(str(result) + '\n')
以上代码实现了按行读取 question.txt 文件中的表达式,并使用 calculate_expression 函数计算每个表达式的结果。最后,将结果按行写入 answer.txt 文件中。
请注意,以上代码的运行依赖于正确的表达式格式和定义的运算函数。如果文件格式或运算函数有任何错误,代码可能无法正常工作。