问题: Lex程序检查给定的数字是否为阿姆斯壮数字。
解释:
Lex是一个生成词法分析器的计算机程序,由Mike Lesk和Eric Schmidt编写。 Lex读取指定词法分析器的输入流,并输出以C编程语言实现词法分析器的源代码。
描述:
阿姆斯壮数字是一个数字,该数字是其自己的数字之和,每个数字均提高为数字的幂。例如,153是阿姆斯特朗编号,
(1^3) + (5^3) + (3^3) = 153
例子:
Input: 153
Output: 153 is a Armstrong number
Input: 250
Output: 250 is not a Armstrong number
执行:
/* Lex program to check whether given
- number is armstrong number or not */
%
{
/* Definition section */
#include
#include
void check(char*);
%
}
/* Rule Section */
% %
[0 - 9]
+ check(yytext);
% %
int main()
{
/* yyin as pointer of File type */
extern FILE* yyin;
yyin = fopen("num", "r");
// The function that starts the analysis
yylex();
return 0;
}
void check(char* a)
{
int len = strlen(a), i, num = 0;
for (i = 0; i < len; i++)
num = num * 10 + (a[i] - '0');
int x = 0, y = 0, temp = num;
while (num > 0) {
y = pow((num % 10), len);
x = x + y;
num = num / 10;
}
if (x == temp)
printf("%d is armstrong number \n", temp);
else
printf("%d is not armstrong number\n", temp);
}
输出: