assembly - 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
解决方案
当执行进入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)
...
推荐阅读
- javascript - Javascript 添加和删除 eventlistner
- python - 错误“无法解码木偶的响应”后继续硒脚本
- node.js - Mongoose保存方法多次保存同一个文档
- angular - 如何将加载器添加到角度材料过滤
- wordpress - 错误:应在 google 搜索控制台中指定“offers”、“review”或“aggregateRating”
- laravel - Laravel 自定义 CronJob 进行 15 天和 x 天的定时调度
- git - 如何使用配置或一些脚本自动处理 git push 到 DEV 分支
- css - 只有 CSS 才能在新选项卡中打开链接
- spring-boot - 为什么每次请求/响应都会更新“X-Auth-Token”?
- c# - XAMPP 一段时间后变得超级慢