2014-02-11 143 views
1

在MIPS中,我很困惑如何讓mod工作。以下是我到目前爲止所提供的代碼。除了mod之外,我可能會有更多的錯誤,但是我覺得這些錯誤是mod誤解的結果。我想要做的就是在這裏得到工作代碼(python):如何在MIPS中正確使用mod運算符?

i = 1 
k = 0 
while i < 9: 
if i % 2 != 0: 
    k = k + i 
i += 1 
print(k) 

要正確轉換爲MIPS。這是我在集會第一槍,所以有可能會比國防部的錯誤,被絆倒了我下面的代碼更多:

# Takes the odd integers from 1 to 9, adds them, 
# and spits out the result. 
# main/driver starts here 
    .globl main 

main: 

#data segment 
.data 

Li:  .byte 0x01 # i = 1 
Lj:  .byte 0x09 # j = 9 
Lk:  .byte 0x00 # k = 0 
Ltwo: .byte 0x02 # 2 for mod usage 

# text segment 
.text 

lb $t0, Li  # temp reg for i 
lb $t1, Lj  # j 
lb $t2, Lk  # k 
lb $t3, Ltwo  # 2 

L1: beq $t0, $t1, L2 # while i < 9, compute 
    div $t0, $t3  # i mod 2 
    mfhi $t6  # temp for the mod 
    beq $t6, 0, Lmod # if mod == 0, jump over to L1 
    add $t2, $t2, $t0 # k = k + i 
Lmod: add $t0, $t0, 1  # i++ 
    j L1   # repeat the while loop 


L2: li $v0, 1  # system call code to print integer 
lb $a0, Lk  # address of int to print 
syscall 

li $v0, 10 
syscall 
+1

您還沒有解釋問題是什麼。代碼的行爲與預期的不同之處是什麼?儘管如此,這些'sb'指令一開始看起來很可疑。 'sb'的目的是將寄存器的低字節寫入存儲器。 – Michael

+0

你完全正確。我在那裏拍了磅,現在代碼至少可以指出問題的關鍵。問題發生在我的第7次迭代中。 k正確地遞增直到那個點。在i = 6時k = 9,這是正確的。但是,下一次迭代將k取爲10而不是正確的答案,16。問題可能在於我如何聲明k,但我不確定。 – kcmallard

回答

3

您在十六進制查看SPIM寄存器。十六進制10是十進制16.

+0

是的。將寄存器顯示從十六進制改爲十進制。 – kcmallard

1

解決了這個問題之後,下面的代碼就像一個魅力一樣。要在MIPS中正確使用mod運算符,必​​須使用HI和LO。我需要i%2 == 0的聲明,所以mfhi派上用場。以下代碼參考工作結果:

# Takes the odd integers from 1 to 9, adds them, 
# and spits out the result. 
# main/driver starts here 
    .globl main 

main: 

#data segment 
.data 

Li:  .byte 0x01 # i = 1 
Lj:  .byte 0x0A # j = 10 
Lk:  .byte 0x00 # k = 0 
Ltwo: .byte 0x02 # 2 for mod usage 


# text segment 
.text 

lb $t0, Li  # temp reg for i 
lb $t1, Lj  # j 
lb $t2, Lk  # k 
lb $t3, Ltwo  # 2 

L1:  beq $t0, $t1, L2 # while i < 9, compute 
     div $t0, $t3  # i mod 2 
     mfhi $t6   # temp for the mod 
     beq $t6, 0, Lmod # if mod == 0, jump over to Lmod and increment 
     add $t2, $t2, $t0 # k = k + i 
Lmod: add $t0, $t0, 1  # i++ 
     j L1    # repeat the while loop 


L2:  li $v0, 1  # system call code to print integer 
     move $a0, $t2  # move integer to be printed into $a0 
     syscall 

     li $v0, 10  # close the program 
     syscall