我该如何在MIPS中正确使用取模运算符?

5
在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

1
你还没有解释问题在哪里。代码的行为与你预期的有何不同?然而,开头的那些 sb 指令看起来很可疑;sb 的目的是将寄存器的低字节写入内存。 - Michael
你说得完全正确。我把lb放进去了,现在代码至少到了我可以确定问题的地方。问题出现在第7次i的迭代中。k在那之前正确递增。在i=6时,k=9是正确的。但是,下一次迭代将k带到10,而不是正确的答案16。问题可能在于我如何声明k,但我不确定。 - kcmallard
2个回答

4

您正在以十六进制查看SPIM寄存器。 十六进制10等于十进制16。


好的。将寄存器显示从十六进制改为十进制就解决了。 - kcmallard
1
但是,在MIPS中如何使用模运算符? - Rainb

4

经过修正,以下代码能够完美运行。在MIPS中正确使用取余操作符,必须使用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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接