代码之家  ›  专栏  ›  技术社区  ›  Christian Peterson

将C代码转换为MIPS迭代阶乘函数

  •  1
  • Christian Peterson  · 技术社区  · 7 年前

    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:
    

    2 回复  |  直到 7 年前
        1
  •  2
  •   paxdiablo    7 年前
    ble $t2, $t4, end_loop #i<=k, end the loop
    

    不,C的第二部分 for 循环,而不是结束它。

    你在这里做的事不公平 $t1 $t2

    您可能想要使用 bgt 而不是 ble

        2
  •  0
  •   Andre Kampling    7 年前

    您的循环条件 ble $t2, $t4, end_loop #i<=k, end the loop 将结束循环,如果 i<=k

    正如在下面代码的注释中所说,我已经实现了一个 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