首页 > 解决方案 > 检查一个数字是否在数组 mips 中

问题描述

所以我必须让这段代码适用于我的班级。基本上我必须找出用户输入的数字是否在预先填充的数组中。到目前为止,这就是我能做的一切......我需要一些帮助来解决剩下的问题。

.data
    array: .word 1, 2, 4, 8, 16, 32, 64, 128, 50, 10
    number: .asciiz "Number to find: "
    true: .asciiz "Number is in array"
    false: .asciiz "Number is not in array"
    quebrarLinha: .asciiz "\n"
    
.text
    la $t0, array
    
    li $v0, 4
    la $a0, numero

    li $t0, 0
    
    addi $t0, $zero, 0
    
    loop:   
        beq $t0, 40, exit
        lw $t6, num($t0)
        
        addi $t0, $t0, 4
        
        
        li $v0, 1
        move $a0, $t6
        syscall
        
        
        li $v0, 4
        la $a0, quebrarLinha
        syscall
        
        j loop
    exit:
    
    li, $v0, 4
    la $a0, numero
    syscall
    
    li, $v0, 5
    syscall
    move $t1, $v0

标签: arrayssearchmipsmars-simulator

解决方案


我知道这有点晚了,但我刚刚在课堂上遇到了一个相同的问题,我终于弄明白了。我的代码和你的很相似。我将发布我的答案以供将来参考:

.data

array: .word 1,2,3,4,5,6,7,8,17,10
prompt: .asciiz "Type in an integer to see if it is in the database: "
found: .asciiz "Number found!"
notfound: .asciiz "No such number found"
newline: .asciiz "\n"

.text
#prompt user
la $a0, prompt
li $v0, 4
syscall
#store user input in t0
li $v0,5
syscall
move $t0, $v0

li $s0, 0 #init counter
loop:
beq $s0,40,nosuchword #loop counter exits at 10 loops


lw $t1,array($s0) #load next database entry 

#debug / print database
move $a0, $t1
li $v0,1
syscall 

la $a0, newline
li $v0, 4
syscall

beq  $t0,$t1,foundword

addu $s0, $s0, 4 #increment counter by 4 (offset size)
j loop

foundword:
la $a0,found
li $v0,4
syscall
j exit

nosuchword:
la $a0, notfound
li $v0,4
syscall

exit:

推荐阅读