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



我对编程很陌生,只有几个月,只是在摆弄一些汇编代码。我的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:

我通过输入一堆 print 语句来测试代码,并且能够获得 $t 4 和 $t 0 作为输入,但在循环后 $t 1 和 $t 2 都保持为 1。我必须跳入循环吗?

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

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

您在这里所做的甚至不是进入循环的主体,这就是为什么$t1$t2保持与初始化它们相同的值。

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

如果i<=k,你带有ble $t2, $t4, end_loop #i<=k, end the loop的循环条件将结束循环,但相反,只要这个条件有效,你就想运行它。对于大于 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

最新更新