当在程序中输入数字4时,我收到一个回答,说阶乘是268501056。显然,这是不正确的。我不太确定我的错误在哪里,我非常感谢您的帮助。
.data
prompt: .asciiz "Enter a number to find the factorial: "
output: .ascii "\n The factorial is "
number: .word 0
answer: .word 0
.text
.globl main
main:
li $v0, 4 #get number from the user to factorial
la $a0, prompt
syscall
li $v0, 5 #value stored in $v0
syscall
sw $v0, number #number user entered is stored in variable number
lw $a0, number #number stored in a0
jal factorial #calling function
sw $v0, answer #value from factorial returned here
li $v0,4 #display output
la $a0, output
syscall
li $v0,1 #display value
la $a0, answer
syscall
li $v0, 10 #end
syscall
factorial:
addi $sp, $sp ,-8 #allocate space in stack to store words
sw $ra, 0($sp) #storing return address to first value in stack
sw $s0, 4($sp) #store variable in stack
#BASE CASE
li $v0, 1
beq $a0, $0, done #if input is equal to 0 return 1 and go to done
#factorial(num-1)
add $s0, $a0, $0 #put value into s0
addi $a0, $a0,-1 #subtract 1 from argument
jal factorial #recursive
mul $v0, $s0, $v0 #multiply values when the function is being popped off the stack
done:
lw $ra, 0($sp) #restoring values of return address
lw $s0, 4($sp) #loading variable back from register to the stack
addi $sp, $sp, 8 #restore stack
jr $ra #return value from function
答案 0 :(得分:2)
执行此操作时:
la $a0, answer
您正在将answer
的地址加载到$ a0中,该值在我的模拟器上为0x10010040 = 268501056。之后,您需要lw $a0, 0($a0)
或类似名称才能真正从该存储位置获得答案。