首页 > 解决方案 > MIPS - 无法找到数组中的最小值

问题描述

所以我得到了一个任务,我应该在 MIPS 汇编语言中找到用户创建的 10 位数组中的最大值和最小值的索引。我已经能够找到最大值,但我无法找到最小值。一旦找到最大值,我认为这应该是一个简单的解决方案,但我错了。

这是我必须找到的最大值:

deleteMax:
# $s7 is the register where the address of the array is stored
# $s0 is the register where the array size is stored

# Clear out unimportant registers
addi $s1, $zero, 0
addi $t0, $zero, 0
addi $s3, $zero, 0
addi $s4, $zero, 0
addi $t6, $zero, 0
addi $t7, $zero, 0

addi $t0, $zero, 0               # Address of first element in bytes
li $t3, -1                       # Max index
li $s2, 0                        # Max value
li $t1, 0                        # Counter


loop:
sll $s1, $t1, 2
add $s1, $s1, $s7
lw $s3, 0($s1)                   # Load the first element into $s3
li $v0, 1
move $a0, $s3
syscall


slt $t2, $s3, $s2      # If $s3 < $s2, $t2 = 1, if $s3 >= $s2, $t2 = 0
bne $t2, $zero, find_max
ori $s2, $s3, 0            # Updates the maximum value
ori $t3, $t1, 0            # Updates the maximum value index

find_max:
addi $t1, $t1,1           # Increase the counter
bne $t1, $s0, loop        # if the counter hasn't reached the end, go 
                          back to the loop
j print_max

这就是我想要的:找到最大值和它的索引。但是,当我尝试切换这两行代码时:

slt $t2, $s3, $s2      # If $s3 < $s2, $t2 = 1, if $s3 >= $s2, $t2 = 0
bne $t2, $zero, find_max

让我们说:

slt $t2, $s3, $s2      # If $s3 < $s2, $t2 = 1, if $s3 >= $s2, $t2 = 0
bne $t2, 1, find_max

最小值为0?

我不确定为什么会发生这种情况,也不确定我可以为目前的情况做些什么来找到最小值。

我希望我已经解释了自己,并且我的代码+评论已经足够解释了这种情况。我非常乐意回答你们可能有的更多困惑。

标签: arraysassemblymipsmips32

解决方案


推荐阅读