接下来,我们在Simpletron上实现一个更复杂一点的程序,计算1+2+3+......+99+100的值,我的设计如下:
有的地方看上去我觉得啰嗦,但是一时间也找不到更好的方法,但是结果是正确的哦,5050,一个经典的数字。
(
PS:这里做这个程序的时候我改了下Simpletron.c,两个地方,原来的exec()方法为:
void exec()
{
int i = 0;
init();
printf("*** Program. execution begins ***/n");
for(i=0; i<100; i++)
{
instructionRegister = i;
instructionRegister = memory[ instructionCounter ];
if (instructionRegister <= 0)
{
error(1);
}
operationCode = instructionRegister/100;
operand = instructionRegister%100;
exechelper();
}
}
结果发祥不管怎样最后结果都是199,只加了一次。后来发现那个4202语句没有意义。又改成如下了:
void exec()
{
init();
printf("*** Program. execution begins ***/n");
while (instructionCounter<100)
{
instructionRegister = memory[ instructionCounter++ ];
if (instructionRegister <= 0)
{
instructionCounter--;
error(1);
}
operationCode = instructionRegister/100;
operand = instructionRegister%100;
exechelper();
}
}
然后OK。
第二个改动是,我觉得我的SML程序写的没有问题,但是偏偏不出来正确的结果,每次输入很麻烦,我就写到文件中,从文件里读出来,不用自己每次命令行输入了。将start()改为了:
void start()
{
int resultOfScanf = 0;//indicate whether scanf() succeed. 0 for false
int scanfed = -1;
char * sml = "sml.sml";
FILE *f = fopen(sml, "r");
if (NULL == f)
{
exit(0);
}
while (fscanf(f, "%d", &scanfed) != EOF)
{
printf("%.2d ? %+.4d/n", instructionCounter, scanfed);
if (abs(scanfed)>9999)
{
printf("[A wrong instruction or data word.(-9999 ~ +9999)]/n");
continue;
}
memory[ instructionCounter++ ] = scanfed;
}
fclose(f);
printf("*** Program. loading completed ***/n");
}
这里没有做很多的正确性判断。连程序文件名sml.sml都确定了。如果大家有兴趣,慢慢调整,改得更好一点,然后请不要忘了告诉我你们改动的结果,让我学习一下。
PS End
)
有的地方看上去我觉得啰嗦,但是一时间也找不到更好的方法,但是结果是正确的哦,5050,一个经典的数字。
(
PS:这里做这个程序的时候我改了下Simpletron.c,两个地方,原来的exec()方法为:
void exec()
{
int i = 0;
init();
printf("*** Program. execution begins ***/n");
for(i=0; i<100; i++)
{
instructionRegister = i;
instructionRegister = memory[ instructionCounter ];
if (instructionRegister <= 0)
{
error(1);
}
operationCode = instructionRegister/100;
operand = instructionRegister%100;
exechelper();
}
}
结果发祥不管怎样最后结果都是199,只加了一次。后来发现那个4202语句没有意义。又改成如下了:
void exec()
{
init();
printf("*** Program. execution begins ***/n");
while (instructionCounter<100)
{
instructionRegister = memory[ instructionCounter++ ];
if (instructionRegister <= 0)
{
instructionCounter--;
error(1);
}
operationCode = instructionRegister/100;
operand = instructionRegister%100;
exechelper();
}
}
然后OK。
第二个改动是,我觉得我的SML程序写的没有问题,但是偏偏不出来正确的结果,每次输入很麻烦,我就写到文件中,从文件里读出来,不用自己每次命令行输入了。将start()改为了:
void start()
{
int resultOfScanf = 0;//indicate whether scanf() succeed. 0 for false
int scanfed = -1;
char * sml = "sml.sml";
FILE *f = fopen(sml, "r");
if (NULL == f)
{
exit(0);
}
while (fscanf(f, "%d", &scanfed) != EOF)
{
printf("%.2d ? %+.4d/n", instructionCounter, scanfed);
if (abs(scanfed)>9999)
{
printf("[A wrong instruction or data word.(-9999 ~ +9999)]/n");
continue;
}
memory[ instructionCounter++ ] = scanfed;
}
fclose(f);
printf("*** Program. loading completed ***/n");
}
这里没有做很多的正确性判断。连程序文件名sml.sml都确定了。如果大家有兴趣,慢慢调整,改得更好一点,然后请不要忘了告诉我你们改动的结果,让我学习一下。
PS End
)