问题描述
.data
n1:.asciiz"Enter the first number:"
n2: .asciiz"Enter the second number:"
.text
.globl main
main:
li $v0,4
la $a0,n1
syscall
li $v0,5 # get input from user
syscall
move $a0,$s0
li $v0,n2
syscall
li $v0,5 # get second input from user
syscall
move $a0,$s1
jal calcGCD # call function calcGCD
add $a0,$v0,$zero
li $v0,1
syscall # print result
li $v0,10 # exit program
syscall
calcGCD:
#GCD(n1,n2)
# n1 = $a0
# n2 = $a1
addi $sp,$sp,-12
sw $ra,0($sp) # save function into stack
sw $s0,4($sp) # save value $s0 into stack
sw $s1,8($sp) # save value $s1 into stack
add $s0,$a0,$zero # s0 = a0 ( value n1 )
add $s1,$a1,$zero # s1 = a1 ( value n2 )
addi $t1,$zero,0 # $t1 = 0
beq $s1,$t1,return # if s1 == 0 return
add $a0,$s1 # make a0 = $s1
div $s0,$s1 # n1/n2
mfhi $a1 # reminder of n1/n2 which is equal to n1%n2
jal calcGCD
exitGCD:
lw $ra,0 ($sp) # read registers from stack
lw $s0,4 ($sp)
lw $s1,8 ($sp)
addi $sp,12 # bring back stack pointer
jr $ra
return:
add $v0,$s0 # return $v0 = $s0 ( n1)
j exitGCD
解决方法
您的代码的主要问题在于您将用户输入存储在寄存器中的部分。在移动 $a0,$s0 中,当用户输入存储在 $v0 中时,您将 $s0 处的值移动到 $a0 中,因此,它应该是移动 $a0,$v0,并且从您的函数中,您似乎有将第二个输入存储在 $a1 中,但在您的代码中,两个输入都存储在同一个寄存器中,因此下一个命令应该是 move $a1,$v0。这是您的代码的一个版本。
.data
n1:.asciiz"Enter the first number:"
n2: .asciiz"Enter the second number:"
.text
.globl main
main:
li $v0,4
la $a0,n1
syscall
li $v0,5 # get input from user
syscall
move $t0,$v0 #temporarily store the user input in another register because $a0 is having another value stored in it in the next command
li $v0,n2
syscall
li $v0,5 # get second input from user
syscall
move $a1,$v0
move $a0,$t0 #transfer the first user input into $a0 to be used in the function
jal calcGCD # call function calcGCD
add $a0,$v0,$zero
li $v0,1
syscall # print result
li $v0,10 # exit program
syscall
calcGCD:
#GCD(n1,n2)
# n1 = $a0
# n2 = $a1
addi $sp,$sp,-12
sw $ra,0($sp) # save function into stack
sw $s0,4($sp) # save value $s0 into stack
sw $s1,8($sp) # save value $s1 into stack
add $s0,$a0,$zero # s0 = a0 ( value n1 )
add $s1,$a1,$zero # s1 = a1 ( value n2 )
addi $t1,$zero,0 # $t1 = 0
beq $s1,$t1,return # if s1 == 0 return
add $a0,$s1 # make a0 = $s1
div $s0,$s1 # n1/n2
mfhi $a1 # reminder of n1/n2 which is equal to n1%n2
jal calcGCD
exitGCD:
lw $ra,0 ($sp) # read registers from stack
lw $s0,4 ($sp)
lw $s1,8 ($sp)
addi $sp,12 # bring back stack pointer
jr $ra
return:
add $v0,$s0 # return $v0 = $s0 ( n1)
j exitGCD