⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 calculator.y

📁 该课程设计通过使用flex和bison编写了一个科学计算器的程序
💻 Y
字号:
%{
#include<math.h>     /* For math functions,sin(),cos(),etc.*/
#include"Calculator.h"     /* contains definition of 'synrec'.*/
#include"Calculator.c"
int yylex(void);
void yyerror(char const*);
%}                   /* End of prologue.*/
%union{
number val;          /* For returning numbers.*/
symrec *tptr;        /* For returning symbol-table pointers.*/
}
%token<val> NUM;      /*Simple double precision numbers.*/
%token<tptr> VAR FNCT /*Variable and Function.*/
%type<val> exp
%right '='
%left '-' '+'
%left '*' '/'
%left NEG            /*negation--unary minus*/
%right '^'           /*exponentiation*/
%%/* The grammar follows*/
input:/*empty*/
      |'\n' 
      |input line
      ;
line:'\n'
    |VAR '=' exp'\n'{{$1->value.var.a=$3.a;$1->value.var.b=$3.b;}
                     if($3.b==0){yyerrok;}} 
    |exp '#''\n'{Display($1);}    /* Display */
    |error'\n'{yyerrok;}          /* Error */
    ;
exp:NUM{$$.a=$1.a;$$.b =1;}
   |VAR{$$.a=$1->value.var.a;$$.b=$1->value.var.b;}
   |VAR '=' exp{$$.a=$3.a;$$.b=$3.b;$1->value.var.a=$3.a;$1->value.var.b=$3.b;}
   |FNCT '(' exp ')'{$$.a=(*($1->value.fnctptr))($3.a/$3.b);$$.b=1;}
   |exp '+' exp{$$.a=$1.a*$3.b+$3.a*$1.b;$$.b=$1.b*$3.b;}
   |exp '-' exp{$$.a=$1.a*$3.b-$3.a*$1.b;$$.b=$1.b*$3.b;}
   |exp '*' exp{$$.a=$1.a*$3.a;$$.b=$1.b*$3.b;}
   |exp '/' exp{$$.a=$1.a*$3.b;$$.b=$1.b*$3.a;}
   |'-' exp %prec NEG{$$.a=-$2.a;$$.b=$2.b;}
   |exp '^' exp{$$.a=pow($1.a,$3.a);$$.b =1;}
   |'(' exp ')'{$$.a=$2.a;$$.b=$2.b;}
   ;
%%
#include<ctype.h>
int yylex(void)
{
  int c;
  while((c=getchar())==' '||c=='\t');

  if(c==EOF) return 0;
  if(c=='.'||isdigit(c))
  { 
    ungetc(c,stdin);
    scanf("%lf",&yylval.val);
    return NUM;
   }
   if(isalpha(c))
   {
     symrec *s;
     static char *symbuf=0;
     static int length=0;
     int i;
     if(length==0)
     length=40,symbuf=(char *)malloc(length+1);
     i=0;
     do{
        if(i==length)
        {
          length*=2;
          symbuf=(char *)realloc(symbuf,length+1);
        }
        symbuf[i++]=c;
        c=getchar();
        }while(isalnum(c));
       ungetc(c,stdin);
       symbuf[i]='\0';
       s=getsym(symbuf);
       if(s==0)
       s=putsym(symbuf,VAR);
       yylval.tptr=s;
       return s->type;
      }
     return c;
 }
    

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -