首页 > 解决方案 > 你可以在 MIPS 中使用多个 BEQ 语句吗?

问题描述

我正在尝试编写一个将 a、b、c 或 d 作为用户输入的代码,然后根据用户的需要对它们进行分支。出于某种原因,当我选择 4 个选项之一时,代码只是穿过所有分支并且程序结束。是因为只能使用一个分支语句吗?

.data
    #messages
    options: .asciiz "\nPlease enter a, b, c or d: "
    youEntered: .asciiz "\nYou picked: "
    bmiMessage: .asciiz "\nThis is the BMI Calculator!"
    tempMessage: .asciiz "\nThis converts Farenheit to Celcius!"
    weightMessage: .asciiz "\nThis converts Pounds to Kilograms!"
    sumMessage: .asciiz "\nThis is the sum calculator!"
    repeatMessage: .asciiz "\nThat was not a, b, c or d!"
    
    #variables
    input: .space   4 #only takes in one character
    
.text
main:
    #display "options" messsage
    li $v0, 4
    la $a0, options
    syscall
    
    #user input 
    li $v0, 8
    la $a0, input
    li $a1, 4
    syscall

    #display "youEntered" messsage
    li $v0, 4
    la $a0, youEntered
    syscall

    #display option picked
    li $v0, 4
    la $a0, input
    syscall

#branching
beq $a0, 'a', bmi
beq $a0, 'b', temperature
beq $a0, 'c', weight
beq $a0, 'd', sum


#end of main
li $v0, 10
syscall

bmi: 
    li $v0, 4
    la $a0, bmiMessage
    syscall

temperature:
    li $v0, 4
    la $a0, tempMessage
    syscall
    
weight: 
    li $v0, 4
    la $a0, weightMessage
    syscall
    
sum: 
    li $v0, 4
    la $a0, sumMessage
    syscall

repeat: 
    li $v0, 4
    la $a0, repeatMessage
    syscall

任何事情都会有帮助谢谢大家!

标签: assemblymipsbranchmars-simulator

解决方案


当您有如下代码时:

label:
    # some code

another_label:
    # some more code

执行后# some code,控制继续到# some more code. 您可能想无条件地跳到主代码的末尾:

label:
    # some code
    j done

another_label:
    # some more code
    j done

# ...

done:
    # end of main

这与您的分支相结合,提供了独特的块语义,如 C链ifelse

if (something) {
   // do something
}
else if (something_else) {
   // do something else
}

// end of main

其次,$a0是地址,而不是值,所以分支比较会失败。尝试将位于该地址的值加载到寄存器中,然后使用该寄存器值与 进行比较'a''b'依此类推。

例如,

lb $t0, input
beq $t0, 'a', bmi
beq $t0, 'b', temperature
beq $t0, 'c', weight
beq $t0, 'd', sum

推荐阅读