【发布时间】:2017-08-20 00:53:13
【问题描述】:
我正在尝试创建一个 mips 汇编程序来递归计算 nCr。
我已经编写了整个程序,包括一个驱动程序,但它不能正常运行。我所有的输入和输出都有效,但我的递归算法返回了疯狂的数字。例如,nCr ==268501120 而不是 10。
更新代码:http://pastebin.com/52ueQu99
这只是我的算法的一个 sn-p:
nCk:
sub $sp, $sp, 16 #allocate the needed space in stack.
sw $ra, 0($sp) #save return address in first position
sw $t3, 4($sp) #save n in the stack
sw $t4, 8($sp) #save k in the stack
sub $t3, $t3, 1 #Subtract one from n
sub $t4, $t4, 1 #Subtract one from k
jal checkBounds #Check for end of recursion.
sw $v0, 12($sp) #copy returned 1 or 0 into stack.
lw $t3, 4($sp) #Load original n back into t3.
lw $t4, 8($sp) #Load original k back into t4.
sub $t3, $t3, 1 #Subtract one from n again. (n-1 step of recursive algorithm)
jal checkBounds #Check for end of recursion with n 1 number lower.
lw $t2, 12($sp) #Load the value held in the previously returned v0.
add $v0, $v0, $t2 #Add old returned value to new returned value.
lw $ra, 0($sp) #Load the original return address.
addi $sp, $sp, 16 #Add 16 more bytes to the stack.
jr $ra
checkBounds: #Check if program should still recurse
beq $t3, $t4, return1 #If n==k
beq $t4, $0, return1 #if k==0
li $v0, 0 #If (j!=k || k!=0){ return 0};
jal nCk
jr $ra
return1: #Returns 1
li $v0, 1
jr $ra
【问题讨论】:
-
你的
printAnswer例程对我来说毫无意义。例如,您在末尾打印的整数值(应该是n)实际上是answerIs字符串的地址,除非我完全弄错了。 -
你很有可能是对的。我不确定哪个参数会保持最终结果。我得出的结论是 t3 持有结果。我想我错了?你知道我该如何解决这个问题吗?再次感谢您的帮助。
-
很可能
$t3在那时持有n- 我没有阅读所有代码。但是$t3不是系统调用 1 的参数;$a0是。因此,您可能需要move $a0,$t3而不是那个la指令。la伪指令用于将某物的地址(通常是标签)加载到寄存器中。 -
哈哈,你说得对!我倒着写了那条指令。我的程序现在运行得稍微好一些。 5c2 现在返回 -1 而不是那个巨大的数字。
标签: assembly recursion mips combinations ncr