2013-04-17 79 views
-1

你好,我在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 
+0

[在MIPS絕對值(http://stackoverflow.com/questions/2312543/absolute-value-in-mips) – Michael

回答

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 
+0

'子$ V0,$零的可能重複,$ v0'會比'nor' /'addi'簡單 – Michael