在MIPS中,我对如何使模运算起作用感到困惑。以下是我迄今为止想出的代码。除了模运算,我可能还有更多错误,但我觉得这些错误是模运算理解上的问题。我只想在这里获得可工作的代码(Python):
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