以mips为单位计算绝对值的函数

时间:2013-04-17 14:45:22

标签: function mips

你好我有一个mips练习,必须调用一个函数来计算一个数字的绝对值

我已经编写了2个代码但是如果你有任何其他解决方案可以写它

.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

,第二个代码就是这个

.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

1 个答案:

答案 0 :(得分:1)

试试这个:

.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

测试:

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