我是编程的新手,才几个月,只是摆弄一些汇编代码。我的 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。我必须跳入循环吗?
最佳答案
ble $t2, $t4, end_loop #i<=k, end the loop
不,C for
语句的第二部分是您希望继续循环而不是结束循环的条件。
您在这里所做的甚至不是进入循环体,这就是为什么$t1
和$t2
保持不变的原因将它们初始化为的值。
您可能想使用 bgt
而不是 ble
。
关于将 C 代码转换为 MIPS - 迭代阶乘函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45841531/