-1

你好,我有一个 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
4

1 回答 1

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
于 2013-04-17T17:23:05.713 回答