我无法将以下C代码转换为MIPS
#include <stdio.h>
int main (void)
{
int n = 0;
printf ("n = ");
scanf ("%d", &n);
int fac = 1;
for (int i = 1; i <= n; i++)
fac *= i;
printf ("n! = %d\n", fac);
return 0;
}
我的代码未打印出预期的结果,但是可以成功打印“ n:”等。
### Global data
.data
msg1:
.asciiz "n: "
msg2:
.asciiz "n! = "
eol:
.asciiz "\n"
### main() function
.data
.align 2
.word 4
.text
main:
la $a0, msg1
li $v0, 4 #printf("n: ")
syscall
li $v0, 5 #scanf("%d", &n)
syscall
li $t0, 1
li $t1, 1
mul $t1, $t1, $t0 #t1 = t1*t0
add $t0, $t0, 1 #t0 = t0+1
la $a0, msg2
li $v0, 4 #printf("n!= ")
syscall
li $v0, 1 #print %d
la $a0, eol
li $v0, 4 #printf("\n")
syscall
li $v0, 0
jr $ra #return from main
我的代码没有产生任何输出,所以我想我的循环中可能出了些问题
答案 0 :(得分:0)
您正在执行的代码的循环部分与c代码中的for循环相对应,并且您没有设置值并为printf(“%d”)代码调用syscall。
### Global data
.data
msg1:
.asciiz "n: "
msg2:
.asciiz "n! = "
eol:
.asciiz "\n"
### main() function
.data
.align 2
.word 4
.text
main:
la $a0, msg1
li $v0, 4 #printf("n: ")
syscall
li $v0, 5 #scanf("%d", &n)
syscall
move $t2, $v0 # n = t2
li $t0, 1 # i = 1
li $t1, 1 # fact = 1
loop:
bgt $t0, $t2, end_loop # i > b - stop looping
mul $t1, $t1, $t0 #t1 = t1*t0
add $t0, $t0, 1 #t0 = t0+1
j loop
end_loop:
la $a0, msg2
li $v0, 4 #printf("n!= ")
syscall
li $v0, 1 #print %d
move $a0, $t1
syscall
la $a0, eol
li $v0, 4 #printf("\n")
syscall
li $v0, 0
jr $ra #return from main