0

大家好,我需要一些帮助将以下 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*=factorial(a-1),我理解 multi 用于将两个寄存器相乘,但它如何获取递归循环的输入?也可以乘以常数而不是另一个寄存器吗?

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
4

1 回答 1

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!!"

它包含评论和解释,因此应该没有问题。

于 2012-10-04T14:59:10.607 回答