首页 > 解决方案 > Mips 数组的元素

问题描述

我得到:

$a0 = 数组的地址

$a1 = 该数组的大小

我必须返回:

$v0 = 最大值

$v1 = max 的位置(基于 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

标签: assemblymips

解决方案


当执行进入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)
    ...

推荐阅读