我被告知:
$ a0 =数组的地址
$ a1 =该数组的大小
我必须返回:
$ v0 =最大值
$ v1 =最大值(基于1的索引)
我的代码按预期的方式用于数组大小= 0,但每次都返回max = {first element},position = 1,而使其他测试均失败。
maxAndArg:
li $v0, -2147483648 # $v0(MAX) is the smallest negative number
li $v1, 0 # $v1(POSITION) starts from zero
li $t3, 0 # $t3(i in a normal language) will be used to loop
li $t4, 0 # $t4 will be used to show the position in the array
L1:
beq $t3,$a1,EXIT # if (i = arrsize) goto EXIT
sll $t4,$t4,2 # $t4 = $t4 * 4
add $t5,$a0,$t4 # $t5 now has the ADDRESS of the $t4 element
lw $t5,0($t5) # $t5 now has the VALUE of the $t4 element
ble $v0,$t5,L2 # if (max =< a[$t4]) goto L2
srl $t4,$t4,2 # $t4 = $t4 / 4 (Original value)
addi $t4,$t4,1 # $t4 = $t4 + 1
addi $t3,$t3,1 # $t3 = $t3 + 1 ((i++))
j L1
L2:
add $v0,$t5,0 # max = $t5
add $v1,$t3,1 # position = $t3
EXIT:
jr $ra #return
答案 0 :(得分:0)
当执行进入L2
时,它不返回循环,而是仅在第一次迭代时存在。您可以输入L2
后使用标签ble
后面的标签来跳回,也可以将其更改为bgt
并跳过if
这样的代码,高级语言。
...
lw $t5,0($t5) # $t5 now has the VALUE of the $t4 element
bgt $v0,$t5,L2 # if (max > a[$t4]) goto L2
# this below will only be executed if a[$t4] >= max
add $v0,$t5,0 # max = $t5
add $v1,$t3,1 # position = $t3
L2:
# else or finally, continuing loop...
srl $t4,$t4,2 # $t4 = $t4 / 4 (Original value)
...