Simpletron模拟器(三)

 接下来,我们在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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值