将C代码转换为MIPS - 迭代因子函数

时间:2017-08-23 13:45:52

标签: c mips factorial

我对编程很陌生,只有几个月的时间,只是在摆弄一些汇编代码。我遇到了MIPS代码的问题,我在打印每个变量的值后将问题缩小到我的循环。它只作为任何整数输入的结果打印1。基本上我试图转换这个:

int fac(int k) {
    int i, f = 1;
    for (i = 1; i <= k; i++) {
        f = f * i;
    }
    return f;
}

对此:

fac:
    move $t4, $t0 #$t0 is the input from the user and $t4 is k in the C code
    li $t1, 1 #$t1 is f in the C code, initialising it to 1
    li $t2, 1 #$t2 is i in the C code, declaring it as 1
    loop:
    ble $t2, $t4, end_loop #i<=k, end the loop
    mul $t1, $t1, $t2 #f=f*i
    addi $t2, $t2, 1
    j loop
    end_loop:

我通过输入一堆打印语句来测试代码,并且能够得到$ t4和$ t0作为输入但是$ t1和$ t2在循环之后保持为1。我是否必须跳入循环?

2 个答案:

答案 0 :(得分:2)

ble $t2, $t4, end_loop #i<=k, end the loop

不,C for语句的第二部分是您要继续循环的条件,而不是结束它。

你在这里做的事情甚至不是进入循环体,这就是为什么$t1$t2保持与你初始化它们相同的值。< / p>

您可能希望使用bgt而不是ble

答案 1 :(得分:0)

使用ble $t2, $t4, end_loop #i<=k, end the loop的循环条件将在i<=k结束循环,但只要您想要运行它,只要此条件是肉食。您的循环实现甚至不会进入更大1的阶乘输入循环。

编辑如以下代码中的评论所述,我实施了一个do {...} while ();循环,这不是OP所要求的。但是代码可以工作。在描述文本下面,真正的答案(for循环实现)如下。

删除end_loop:标签,然后跳转到loop:标签,而ble作为最后一条语句:

fac:
    move $t4, $t0 #$t0 is the input from the user and $t4 is k in the C code
    li $t1, 1 #$t1 is f in the C code, initialising it to 1
    li $t2, 1 #$t2 is i in the C code, declaring it as 1
    loop:
    mul $t1, $t1, $t2 #f=f*i
    addi $t2, $t2, 1
    ble $t2, $t4, loop #i<=k, loop goes on if not this doesn't jump

<击>

要实施for循环,您已要求更改ble<=):

ble $t2, $t4, end_loop #i<=k, end the loop

bgt>):

bgt $t2, $t4, end_loop #i>k, end the loop