Mips元素的元素

问题描述 投票:0回答:1

我给了:

$ 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
assembly mips
1个回答
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)
    ...
© www.soinside.com 2019 - 2024. All rights reserved.