Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

if statement - If greater than or equal in MIPS

Prompt for and input two integers “a” and “b” using syscalls

Display one of the following statements depending on if a>b, or a=b or a

  • You entered a greater than b

  • You entered an equal to b

  • You entered a less than b

I have to get this prompt and I tried so hard to get it done. This is where I'm stucked, I'd really appreciate your help.

    .data  
p1: .asciiz "Please enter the first number ? "  
p2: .asciiz " Please enter the second number? "  
ans1: .asciiz " 
You entered a greater than b "  
ans2: .asciiz " 
You entered a equal to b "  
ans3: .asciiz " 
You entered a less than b "  


        .text
        .globl main

main:    
    li $v0, 4     #system call code for print_str  
    la $a0, p1  #address of string to print  
    syscall     #print the first prompt  


    li $v0, 5   #system call code for read_int
    syscall     #read first integer
    move $t1, $v0   #store it till later

    li $v0, 4   #system call code for print_str
    la $a0, p2  #address of string to print
    syscall     #prints the second prompt

    li $v0, 5   #system call code for read_int
    syscall     #read first integer
    move $t2, $v0   #store it till later

    slt $t1,$s1,$s0      # checks if $s0 > $s1
    beq $t1,1,label1 

I really don't know how to use branch statements, and it's really confusing. I would like to know how to fix it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why do you read the numbers into $t1 and $t2 then compare $s1 and $s0? Where is it confusing?

Simply use slt and beq/bne, that'll cover all comparison cases you need.

Suppose a is in $s0, b is in $s1

  • a < b:

    slt $t0, $s0, $s1
    bne $t0, $zero, a_lt_b # $t0 == 1 != 0 if a < b
    
  • a = b:

    beq $s0, $s1, a_eq_b   # nothing more to explain
    
  • a > b:

    slt $t0, $s1, $s0
    bne $t0, $zero, b_lt_a # $t0 == 1 != 0 if b < a
    
  • a >= b:

    slt $t0, $s0, $s1
    beq $t0, $zero, a_ge_b # $t0 == 0 if a >= b or !(a < b)
    
  • a <= b:

    slt $t0, $s1, $s0
    beq $t0, $zero, b_ge_a # $t0 == 0 if b >= a or !(b < a)
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...