【发布时间】:2017-03-08 14:56:55
【问题描述】:
我正在努力寻找前缀翻译方案的中缀。
我已经找到了后缀翻译方案的中缀:
expr -> Term, Rest
Rest -> +Term, { print('+') } , Rest | -Term, { print('-') }, Rest | epsilon
Term -> Factor, Rest_
Rest_ -> *Factor, { print('*') }, Rest_ | /Factor, { print('/') }, Rest_ | epsilon
Factor -> Digit | (expr)
Digit -> 0,1,2,3,4,5,6,7,8,9
和我的中缀到后缀的转换代码按照上面的翻译方案:
#include<iostream>
using namespace std;
const char input[] = "9-5*2";
int index = 0;
char LookAhead = input[index];
void Match(char newChar);
void Factor();
void Rest_();
void Rest();
void Term();
void Expression();
int main(){
Expression();
return 0;
}
void Match(char newChar){
if(newChar == LookAhead){
index++;
LookAhead = input[index];
}
}
void Expression(){
Term();
Rest();
}
void Term(){
Factor();
Rest_();
}
void Rest(){
if(LookAhead == '+'){
Match('+');
Term();
cout << '+';
Rest();
}else if(LookAhead == '-'){
Match('-');
Term();
cout << '-';
Rest();
}else{
}
}
void Rest_(){
if(LookAhead == '*'){
Match('*');
Factor();
cout << '*';
Rest_();
}else if(LookAhead == '/'){
Match('/');
Factor();
cout << '/';
Rest_();
}else{
}
}
void Factor(){
if(isdigit(LookAhead)){
cout << LookAhead;
Match(LookAhead);
}
}
所以现在有没有高手可以帮我理解中缀到前缀转换的翻译方案,不胜感激。
我们可以通过解析树进行测试。如果我们可以从示例字符串 9-5+2 生成类似 -9+52 前缀字符串。
如果我需要解释更多关于我的中缀到后缀转换的翻译方案和代码以便更好地理解,请告诉我。
提前致谢!
已编辑: 只是我在找出前缀表达式转换翻译方案的中缀时遇到问题。举个例子, 我的意见:
9-5+2
预期输出:
-9+52
我想用我上面展示的相同结构来实现这一点,通过中缀到后缀的转换。 就是这样!
【问题讨论】:
-
您的代码是否可以正常工作,而您只需要代码审查?然后在codereview.stackexchange.com 上发帖。如果它不起作用,那么您需要详细说明您的问题(例如向我们展示一些特定的输入、预期和实际输出,以及您尝试调试问题的内容)。如果你已经完成了,那么请花点时间read about how to ask good questions。
-
搜索反向波兰表示法
-
@EdHeal 你能详细说明一下吗
-
@Ray Just google。
-
谷歌一下。将中缀转换为后缀。可以找到算法来做到这一点
标签: c++ compiler-construction parse-tree