大家好我需要帮助将以下C代码转换为MIPS:
main()
{
int i;
for (i=0;i<5;++i)
power(2,1)
factorial(i)
return 0;
}
int power(int base,int n)
{
int i,p;
p=0;
for(i=1;i<=n;++i)
p=p*base;
return p;
}
int factorial(int a)
{
if(a==1)
return 1;
else
{
a *=factorial(a-1);
return a;
}
}
到目前为止我只完成了阶乘部分,但我坚持在* =阶乘(a-1),我认为多用于将两个寄存器相乘但是如何才能输入递归环?是否可以多次乘以常数而不是另一个寄存器?
factorial:
addi $sp, $sp, -8 #adjust stack for 2 items
sw $ra, 4($sp) #save return address
sw $a0, 0($sp) #save argument
bne $a0, 1, Else #if !(a==1), go to else address
addi $v0, $zero, 1 #result is 1
addi $sp, $sp, 8 #pop 2 items from stack
jr $ra #return
Else: addi $a0, $a0, -1 #decrement s-1
jal factorial #recursive call
lw $a0, 0($sp) #restore original a
lw $ra, 4($sp) #and return address
addi $sp, $sp, 8 #pop two items from stack
答案 0 :(得分:0)
这是我写的代码,我认为它符合您的目的。
.text
factorial:
li $t0,13 # load 13 to check for overflow
blt $a0,$t0,no
li $v1,1
no:
bgtz $a0,find # if $a0>0 goto generic case
li $v0, 1 # base case, 0! = 1
jr $ra
find: sub $sp,8 # make room for $s0 and $ra
sw $s0,($sp) # store argument $s0=n
sw $ra,4($sp) # store return address
move $s0, $a0 # save argument
sub $a0, 1 # factorial(n-1)
jal factorial # v0 = (n-1)!
mul $v0,$s0,$v0 # n*(n-1)!
lw $s0,($sp) # restore $s0=n
lw $ra,4($sp) # restore $ra
add $sp,8 # reduce stack size
jr $ra # return
main:
la $a0,input
li $v0,4
syscall
li $v0,5
syscall
move $a0,$v0
jal factorial
move $t0,$v1
bnez $t0,overflow1
move $a0,$v0
li $v0,1
syscall
b end
overflow1:
la $a0,overflow
li $v0,4
syscall
end:
li $v0,10
syscall
.data
input:.asciiz"Input a number:"
overflow:.asciiz"There is an overflow!!"
完整的评论和解释,所以不应该有问题。