您好我正在尝试在汇编代码中实现mccarthy 91函数。当我运行我的代码时,它组装没有错误但是当我输入n的值时,程序获得运行时异常地址超出范围。我查看了我的代码,但我无法找到为什么会这样。
发生错误 sw $ra, 0($sp) #save return address
试图实施的代码:
def mcc91(n):global countcount += 1
if n > 100:
n -10
else:
return mcc91(mcc91(n + 11))
代码:
main:
#Build stack frame
subu $sp, $sp, 32 #stack frame is 32 bytes long
sw $ra, 20($sp) #save return address
sw $fp, 16($sp) #save old frame pointer
addiu $fp, $sp, 28 #set up frame pointer
li $v0, 4 #system call code for print_str
la $a0, prompt #address of string to print
syscall #print the string
li $v0, 5 #system call for read_int
syscall #read n
move $t0, $v0 #and store it
move $a0, $t0 #move the argument
move $t9, $zero #clear the count
jal mcc #call the mcc function
move $s0, $v0 #get the answer returned from mcc and save it
li $v0, 4 #system call code for print_str
la $a0, ans #address of string to print
syscall #print the ans string
move $a0, $s0 #move answer to get ready to print
li $v0, 1 #system call code for print_int
syscall #print answer
li $v0, 4 #system call code for print_str
la $a0, count #address of string to print
syscall #print count string
move $a0, $t9 #get count ready to print
li $v0, 1 #system call code for print_int
syscall #print count
#tear down stack frame
lw $ra 20($sp) #restore return address
lw $fp, 16($sp) #restore frame pointer
addiu $sp, $sp, 32 #pop stack frame
li $v0, 10 #exit program
mcc:
addi $t9, $t9, 1 #increment global count
#Build stack frame
subu $sp, $sp, 12 #stack frame is 32 bytes long
sw $ra, 0($sp) #save return address
sw $a0, 4($sp) #save n
bgt $a0, 100, base #base call
addi $a0, $a0, 11 #add 11 to n
jal mcc #mcc91(n+11)
move $a0, $v0 #n = mcc91(n + 11)
jal mcc #do outer recursion
j done
base:
subi $a0, $a0, 10 #subtract 10 from n
done: #result is in $v0
#tear down the stack frame
lw $ra, 0($sp) #restore $ra
lw $a0, 4($sp) #restore n
addiu $sp, $sp, 12 #pop stack
jr $ra #return to caller
答案 0 :(得分:1)
这里出现问题:
move $a0, $v0 #n = mcc91(n + 11)
您尝试将之前调用的返回值mcc
移至$a0
,但您实际上并未将返回值放在$v0
中。因此,您需要更改此部分:
base:
subi $a0, $a0, 10 #subtract 10 from n
成:
base:
subi $v0, $a0, 10 # return n - 10
我尝试了这个改变的程序并且得到了答案= 93,对于n = 103,count = 1,对于n = 99,得分= 91,count = 5,这对我来说似乎是正确的。