编译原理——无符号数识别

实现思路

无符号数的识别已经在课上做过详细的讲解,其主要实现思想可参考无符号数识别的状态转换图,这里不做赘述。
Alt text

测试样例

程序的测试用例及测试结果如下,可以看到,程序可以正确识别满足格式要求的无符号数,最终以要求格式整数E指数的形式输出。:
Alt text
Alt text

代码实现

下面来简单列支程序子函数代码

辅助全局变量

为了达到识别输入的无符号数的功能,首先需要预设几个全局变量,其变量名及解释如下:

1
2
3
4
int w=0;//整数累加器(初值为0)
int p=0;//指数累加器(初值为0)
int n=0;//十进小数累加器(初值为0)
int e=1;//十进指数的符号(初值为1, 遇负号为-1)

子函数:判断是否为无符号数

无符号数以string类型变量接收,通过bool isnum(string num)函数来实现判别,即最终状态如果落在1、2、6则为无符号数,函数的实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//判断是否为无符号数
bool isnum(string num){

int state = 0;
int i=0;
for(;i<num.size();i++){
char temp = num[i];
state = next_state(state, temp);
if(state==-1)
return false;
}
//没有到达终态1、2、6
if(state==3||state==4||state==5)
return false;
return true;
}

子函数:获取下一状态

bool isnum(string num)函数中需要用到另一个辅助函数int next_state(int currentstate,char temp)来求取下一状态,其实现主要依托switch-case架构,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
//获取下一个状态及中间量计算结果
int next_state(int currentstate,char temp){
int next=-1;

switch (currentstate) {
case 0:{
if(isdigit(temp)){
n=0;
p=0;
e=1;
w=(temp-'0');
next=1;
}
else if(temp=='.'){
n=0;
p=0;
e=1;
w=0;
next=3;
}
else
next=-1;
break;
}

case 1:{
if(isdigit(temp)){
w=w*10+(temp-'0');
next=1;
}
else if(temp=='.'){
next=2;
}
else if(temp=='E'||temp=='e'){
next=4;
}
else
next=-1;
break;
}

case 2:{
if(isdigit(temp)){
w=w*10+(temp-'0');
n=n+1;
next=2;
}
else if(temp=='E'||temp=='e'){
next=4;
}
else
next=-1;
break;
}

case 3:{
if(isdigit(temp)){
n=n+1;
w=w*10+(temp-'0');
next=2;
}
else
next=-1;
break;
}

case 4:{
if(isdigit(temp)){
p=p*10+(temp-'0');
next=6;
}
else if(temp=='+'){
next=5;
}
else if(temp=='-'){
e=-1;
next=5;
}
else
next=-1;
break;
}

case 5:{
if(isdigit(temp)){
p=p*10+(temp-'0');
next=6;
}
else
next=-1;
break;
}

case 6:{
if(isdigit(temp)){
p=p*10+(temp-'0');
next=2;
}
else
next=-1;
break;
}
}
return next;
}

主函数

至此,无符号数的识别功能全部实现,只需要在主函数中循环接受输入并判断即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main(int argc, const char * argv[]) {
while(1){
string num;
cout<<"input:";
cin>>num;

if(isnum(num)){
cout<<"it is an unsigned number~\n";
if(e*p-n!=0&&w!=0)
cout<<"the number is:"<<w<<"E"<<e*p-n<<endl<<endl;
else
cout<<"the number is:"<<w<<endl<<endl;
}
else{
cout<<"it isn't an unsigned number!"<<endl<<endl;
}
}
return 0;
}

小手一抖⬇️