我的任务是编写一个递归 MIPS 汇编程序,该程序在 function1 中执行以下数学运算:
(-3)*function1(n-2) + 7*function1(n-3) + 15
该程序在c中建模:
// The function1 is a recursive procedure defined by:
// function1(n) = 1 if n <= 2
// = (-3)*function1(n-2) + 7*function1(n-3) + 15 otherwise.
int function1(int n)
{
if (n <= 2)
{
return 1;
}
else
{
int comp = (-3)*function1(n-2) + 7*function1(n-3) + 15;
return comp;
}
}
// The main calls function1 by entering an integer given by a user.
void main()
1 of 2{
int ans, n;
printf("Enter an integer:\n");
// read an integer from user and store it in "n"
scanf("%d", &n);
ans = function1(n);
// print out the solution computed by function 1
printf("The solution is: %d\n", ans);
return;
}
我已经编写了代码,它编译和执行得很好,但给了我不正确的值:
.data
mes1: .asciiz "\nEnter an integer: "
mes2: .asciiz "The solutinon is: "
.text
.globl main
main:
#Display message
la $a0, mes1
li $v0, 4
syscall
#Retrieve Value
li $v0, 5
syscall
#Store value into $a0 and jump to function1
move $a0, $v0
jal function1
#Store return value to $t0
move $t0, $v0
#Display solution
la $a0, mes2
li $v0, 4
syscall
move $a0, $t0
li $v0, 1
syscall
#End
li $v0, 10
syscall
function1:
#Store return address
addi $sp, $sp, -4
sw $ra, 0($sp)
#Store $a0 to stack
addi $sp, $sp, -4
sw $a0, 0($sp)
#If($a0<3):$t0=1:$t0=0
slti $t0, $a0, 3
#if($t0=0):math
beq $t0, $zero, math
addi $v0, $zero, 1
#Retrieve from stack
lw $a0, 0($sp)
addi $sp, $sp, 4
lw $ra, 0($sp)
addi $sp, $sp, 4
jr $ra
math:
addi $a0, $a0, -2
jal function1
mul $s0 $v0, -3
addi $a0, $a0, -3
jal function1
mul $s1, $v0, 7
add $s1, $s0, $s1
addi $v0, $s1, 15
#Retrieve from stack
lw $a0, 0($sp)
addi $sp, $sp, 4
lw $ra, 0($sp)
addi $sp, $sp, 4
jr $ra
当我输入 6 时,它应该输出 91。目前,它正在输出 44。也许更令人不安的是,每当我输入任何值时,输出数字总是能被 4 整除。对于我的生活,我无法弄清楚什么是错误的。任何人都可以建议吗?
-编辑-
我考虑了@Tomás Badan 关于保护 $a0 的评论。我试过:
math:
#Store $a0 to stack
addi $sp, $sp, -4
sw $a0, 0($sp)
addi $a0, $a0, -2
jal function1
mul $s0, $v0, -3
#Retrieve from stack
lw $a0, 0($sp)
addi $sp, $sp, 4
addi $a0, $a0, -3
jal function1
mul $s1, $v0, 7
add $s1, $s0, $s1
addi $v0, $s1, 15
#Retrieve from stack
lw $a0, 0($sp)
addi $sp, $sp, 4
lw $ra, 0($sp)
addi $sp, $sp, 4
jr $ra
但它仍然返回不正确的值,尽管更接近正确的数字。