- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在测试使用 bison flex 编写中缀计算器的示例。我发现除了括号“()”之外,其他都正确。我发现当我输入带括号的计算时,计算结果不正确。这是文件“infix-calc.y”的代码
/* bison grammar file for infix notation calculator */
%{
#define YYSTYPE double
#include <math.h>
#include <stdio.h>
int yyerror(const char *s);
int yylex(void);
%}
%token NUM
%left '-' '+'
%left '*' '/'
%left NEG
%right '^'
%% /* Grammer rules and actions follow */
input: /* empty */
| input line
;
line: '\n'
| exp '\n' { printf("\t%.10g\n", $1); }
;
exp: NUM { $$ = $1; }
| exp '+' exp { $$ = $1 + $3; }
| exp '-' exp { $$ = $1 - $3; }
| exp '*' exp { $$ = $1 * $3; }
| exp '/' exp { $$ = $1 / $3; }
| '-' exp %prec NEG { $$ = -$2; }
| exp '^' exp { $$ = pow($1, $3); }
| '(' exp ')' { $$ = $2; }
;
%%
/* Additional C code */
int main() { return yyparse(); }
int yyerror(const char* s)
{
printf("%s\n", s);
return 0;
}
这里是文件“infix-calc.lex”的代码
/* lex file for infix notation calculator */
%option noyywrap
%{
#define YYSTYPE double /* type for bison's var: yylval */
#include <stdlib.h> /* for atof(const char*) */
#include "infix-calc.tab.h"
%}
digits [0-9]
rn (0|[1-9]+{digits}*)\.?{digits}*
op [+*^/\-]
ws [ \t]+
%%
{rn} yylval = atof(yytext); return NUM;
{op} |
\n return *yytext;
{ws} /* eats up white spaces */
%%
问题是,当我输入“2 * (3 + 4)”时,我应该会收到输出“14”。但是输入的是“() 10”。在这种情况下,括号似乎不起作用。这些代码有什么问题?非常感谢大家对我的帮助!!!!
最佳答案
看起来您必须将 (
和 )
声明为标记才能使其正常工作。
在您的 lex 文件中的最后一个 %%
之前添加以下两行:
"(" return LEFT;
")" return RIGHT;
然后添加
%token LEFT RIGHT
到infix-calc.y的顶部,并替换
| '(' exp ')' { $$ = $2; }
与
| LEFT exp RIGHT { $$ = $2; }
关于c - 如何实现具有优先级和结合性的中缀计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40082230/
前缀表达式 前缀表达式又称波兰式,前缀表达式的运算符位于操作数之前。 例如: ( 3 + 4 ) × 5 − 6 (3+4)×5-6(3+4)×5−6 对应的前缀表达式就是 - × + 3 4 5 6
众所周知: ((.).(.)) :: (b -> c) -> (a -> a1 -> b) -> a -> a1 -> c 我可以像这样使用这个复合运算符前缀样式: ((.).(.)) f g 但看起
换句话说,我可以使用什么语法(如果有)来代替 XXX在过滤器的以下实现中: filter' :: (a -> Bool) -> [a] -> [a] filter' _ [] = [] fil
在 R 中,每当两个包定义相同的函数时,很容易指定使用哪个包 pkg::foo .但是当冲突的函数是中缀运算符时你怎么办,即使用 %% 定义? 例如,ggplot2和 crayon定义 %+% .有没
关于代码的简短介绍:我必须创建一个类来计算前缀、后缀或中缀表达式。它必须判断是否是pre/post/infix并将其转换为后缀,例如从'/x7'转换的代码中的prefixTOpostfix()(其他已
前缀表达式(波兰表达式) 前缀表达式又称波兰表达式,前缀表达式的运算符位于操作符之前,如(3+4)*5-6对应的前缀表达式就是- * + 3 4 5 6 前缀表达式的计算机求
我需要使用 VBA 对数学表达式进行标记。我有一个可行的解决方案,但正在寻找一种更有效的方法(可能是 RegExp)。 我当前的解决方案: Function TokeniseTheString(str
我正在编写一个包含如下函数的包: "%IN%" 0 当我 Build & Reload 包时(我使用 RStudio),这个函数不可用,与包中定义的所有其他函数相反。 我如何使它工作? 最佳答案 解
我一直在用 Java 开发表达式求值器,出于沮丧,我也来这里询问。到目前为止,我至少重写了 15 次,但每次都无济于事。 基本上我需要在前缀、中缀或后缀中获取一个字符串并将其计算为整数。该表达式可以使
C++ 中的运算符通常被认为是函数/方法的替代语法,尤其是在重载的上下文中。如果是这样,下面的两个表达式应该是同义词: std::cout & __out, char __c) operator& _
我是一名优秀的程序员,十分优秀!