-1

hello i have an exercise in mips that must call a function to calculates the absolute value of a number

i have write 2 codes but if you have any other solution write it

.data

message:.asciiz "give number: "

.text

main: 
li $v0, 4       
la $a0, message     
syscall         

li $v0, 5       
syscall         

add $t1, $v0, $zero 

 jal absolute

add $v0,$t2,$zero

li $v0, 1

syscall

li $v0, 10
 syscall 

absolute: ori $t2,$t1,0 #copy r1 into r2
    slt $t3,$t1, $zero      #is value < 0 ?

    beq $t3,$zero,gg #if r1 is positive, skip next inst

    sub $t2,$zero, $t0      #r2 = 0 - r1

 jr $ra

gg:

#t2

and the second code is this

.data

question: .asciiz "give number"

.text
main:
li $v0, 4

la $a0, question

syscall

li $v0, 5

syscall
jal absolute
li $v0, 1

syscall

li $v1, 1

syscall

li $v0, 10

syscall
absolute:

slti $t0,$a0,0

bne $t0,$zero,g1
add $v0,$a0,$zero

jr $ra
g1:

sub $t2,$a0,$a0

sub $v1,$t2,$a0

j absolute
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
user2290590
  • 1
  • 1
  • 2

1 Answers1

1

Try this:

.data
    message:    .asciiz "Enter the number: "
.text
.globl main

main:
    # print message
    li  $v0, 4
    la  $a0, message
    syscall

    # read integer
    li  $v0, 5
    syscall

    slt  $t0, $v0, $0       # $t0 = ( $v0 < 0 ? 1 : 0 )
    bne  $t0, $0, NEGATIVE  # if($t0 != 0) goto NEGATIVE
    j    POSITIVE           # goto POSITIVE (and dose nothing)

NEGATIVE:
    # ~$v0 + 1
    nor  $v0, $v0, $0       # NOR with zero = NOT
    addi $v0, $v0, 1        # $v0 =+ 1

POSITIVE:
    # print $v0
    move $a0, $v0
    li  $v0, 1
    syscall

    # print new line '\n'
    li  $v0, 11
    addi $a0, $0, 10
    syscall

    jr  $ra

Test:

Enter the number: 10
10
Enter the number: -5
5