📜  Lex程序可计算正数,负数和分数

📅  最后修改于: 2021-06-28 07:17:27             🧑  作者: Mango

问题:编写一个Lex程序以计算正数,负数和分数

解释 :
FLEX(快速词法分析器生成器)是一种工具/计算机程序,用于生成Vern Paxson于1987年左右在C中编写的词法分析器(扫描器或词法分析器)。Lex读取指定词法分析器的输入流,并输出在C语言中实现词法分析器的源代码编程语言。函数yylex()是运行规则部分的主要flex函数。

先决条件: Flex(快速词法分析器生成器)

例子:

Input: 2 -8 -2.5 8.5 
Output: No. of positive numbers: 1
        No. of Negative numbers: 1
        No. of Positive numbers in fractions: 1
        No. of Negative numbers in fractions: 1 

Input: 1 2 3 -4 -5 6.5 7.5 
Output: No. of positive numbers: 3
        No. of Negative numbers: 2
        No. of Positive numbers in fractions: 2
        No. of Negative numbers in fractions: 0 

执行:

/* Lex program to Count the Positive numbers, 
      - Negative numbers and Fractions  */
  
%{
     /* Definition section */
    int postiveno=0;
    int negtiveno=0;
    int positivefractions=0;
    int negativefractions=0;
%}
  
/* Rule Section */
DIGIT [0-9]
%%
  
\+?{DIGIT}+             postiveno++;
-{DIGIT}+               negtiveno++;
  
\+?{DIGIT}*\.{DIGIT}+   positivefractions++;
-{DIGIT}*\.{DIGIT}+     negativefractions++;
. ;   
%%
  
// driver code
int main()
{
    yylex();
    printf("\nNo. of positive numbers: %d", postiveno);
    printf("\nNo. of Negative numbers: %d", negtiveno);
    printf("\nNo. of Positive numbers in fractions: %d", positivefractions);
    printf("\nNo. of Negative numbers in fractions: %d\n", negativefractions);
    return 0;
}

输出: