在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
您還沒有解釋問題是什麼。代碼的行爲與預期的不同之處是什麼?儘管如此,這些'sb'指令一開始看起來很可疑。 'sb'的目的是將寄存器的低字節寫入存儲器。 – Michael
你完全正確。我在那裏拍了磅,現在代碼至少可以指出問題的關鍵。問題發生在我的第7次迭代中。 k正確地遞增直到那個點。在i = 6時k = 9,這是正確的。但是,下一次迭代將k取爲10而不是正確的答案,16。問題可能在於我如何聲明k,但我不確定。 – kcmallard