Turing机UN+1的C语言实现
一、题目分析
对于任意给定的字符串w(w不含空格),编程模拟Turing机UN+1的运行过程,要求输出从开始运行起的每一步骤的结果。
二、算法构造
Turing机UN+1的定义:
00→00R
01→11R
10→01STOP
11→11R
三、算法实现
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
int main()
{
char a[20]; //paper tape
int i,len,flag; //len is length of character array,flag is internal state
flag = 0; //initialize internal state
printf("Please Input BINARY System data:");
scanf("%s",&a);
len = strlen(a); //calculate length of character array
clock_t startTime = clock();
for(i=0;i<=len;i++) //specific operation function
{
if(flag == 0&&a[i] == '0') //00→00R
{
flag = 0;
a[i] = '0';
printf("FIRST:%s\n",a);
}
if(flag == 0&&a[i] == '1') //01→11R
{
flag = 1;
a[i] = '1';
printf("SECOND:%s\n",a);
}
if(flag == 1&&a[i] == '0') //10→01STOP
{
flag = 0;
a[i] = '1';
printf("THIRED:%s\n",a);
break;
}
if(flag == 1&&a[i] == '1') //11→11R
{
a[i] = '1';
printf("FOURTH:%s\n",a);
}
}
printf("The Result of UN+1 is %s\n",a);
clock_t endTime = clock();
printf("The TIME Spent by this Program is:%fs.\n",double(endTime - startTime) / CLOCKS_PER_SEC);
system("pause");
return 0;
}
四、调试、测试及运行结果
1、调试
(1)输入数据1010110。
(2)进行第一步运算:01→11R,结果为1010110。
(3)进行第二步运算:11→11R,结果为:1010110。
(4)进行第三步运算:10→01STOP,结果为:1110110。
(5)输出Turing机UN+1的结果:1110110。
2、测试
测试代码:
clock_t startTime = clock();
............
clock_t endTime = clock();
printf("The TIME Spent by this Program is:%fs.\n",double(endTime - startTime) / CLOCKS_PER_SEC);
system("pause");
测试截图:
3、运行结果
五、经验归纳
1、求字符数组长度
strlen()函数求出的字符串长度为有效长度,既不包含字符串末尾结束符‘\0’;sizeof()操作符求出的长度包含字符串末尾的结束符‘\0’;当在函数内部使用sizeof()求解由函数的形参传入的字符数组的长度时,得到的结果为指针的长度,既对应变量的字节数,而不是字符串的长度,此处一定要小心。
2、测试代码
clock_t 在源代码中我们可以看到,它的类型为长整形(long)。
clock()函数返回程序执行起(一般为程序的开头),处理器时钟所使用的时间(ms)。
CLOCKS_PER_SEC数值上等于1000。
为了获取 CPU 所使用的秒数,需要除以 CLOCKS_PER_SEC。
定义个开始时间和结束时间,要测试的程序就放在这两段代码中间。
double(endTime - startTime) / CLOCKS_PER_SEC 得到的就是程序运行的秒数。