将 C 代码转换为 MIPS - 迭代阶乘函数
Converting C code to MIPS - Iterative Factorial Function
我对编程还很陌生,刚接触几个月,只是在摆弄一些汇编代码。我 运行 我的 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
。
如果 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
我对编程还很陌生,刚接触几个月,只是在摆弄一些汇编代码。我 运行 我的 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
。
如果 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