【发布时间】:2016-04-28 01:15:02
【问题描述】:
我正在尝试用 C 编写图灵机。 但是我的程序不起作用,它陷入了无限循环。 这是我的代码和一些解释:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 3 //number of different states for the cells
#define K 20 //length of the tape
typedef struct
{
int state;
int head;
char tape[];
}mt; //machine
void init_mt(mt* machine, char val[], int n)
{
machine->state=1; //edited mistake
machine->head=0; // edited mistake
int i;
for(i=0;i<n;i++)
{
machine->tape[i]=val[i];
}
}; //initialization of a machine
typedef struct
{
char write;
char direction;
int state;
}actions; //actions composed of three instructions
typedef struct
{
actions exec01;
actions exec02;
actions exec11;
actions exec12;
}program; //program composed of four actions
void execute(actions exec, mt mach)
{
mach.tape[mach.head] = exec.write;
mach.state = exec.state;
if(exec.direction == 'R')
{
mach.head++;
}
else
{
mach.head--;
}
} //class that follows the instructions from the actions
void execute2(mt mach, program p)
{ do{
printf("%c %d %d \n", mach.tape[mach.head], mach.head, mach.state );
if(mach.tape[mach.head] == 0)
{
if(mach.state == 1)
{
execute(p.exec01, mach);
}
else if(mach.state == 2)
{
execute(p.exec02,mach);
}
}
else if(mach.tape[mach.head] == 1)
{
if(mach.state == 1)
{
execute(p.exec11,mach);
}
else if(mach.state == 2)
{
execute(p.exec12,mach);
}
}
}while( (mach.head<K) && (mach.state != 3));
} // class that read the program and act according to the states of the cells,
//keeps going until the machine is at the third state or if it reaches the end of the tape
int main(){
mt machine;
char t[10]={'1','1','1','0','0','1','0','1','0','1'};
init_mt(&machine, t, 10);
program p ={ {'0','R',1}, {'0','R',1}, {'1','R',2}, {'0','L',3} };
execute2(machine, p);
return 0;
} //main with a tape composed of 10 cells and a program composed of four actions
这个程序无限期地显示“0,0,1”,我找不到错误。 感谢您的帮助,如果不清楚,我们深表歉意。
【问题讨论】:
-
这不会编译。
mt没有成员etat和tete。发布您实际使用的代码怎么样? -
大概您希望
exec修改“the”图灵机,而不是您传递给它的 copy,对吧?为什么void f(int x) {x++;} int main() {int i = 5; f(i); printf("%i\n", i); return 0;}不打印 6? -
mt machine; .. init_mt(&machine, t, 10);但machine.tape没有内存。 -
感谢您的回答。
-
@TomKarzes 抱歉,我认为翻译类的名称以使其更清晰会更容易,我对其进行了编辑,现在可以使用。
标签: c turing-machines