如何在MIPS中正确使用mod运算符?

2024-05-19 23:02:40 发布

您现在位置:Python中文网/ 问答频道 /正文

在MIPS中,我对如何让国防部工作感到困惑。下面是我到目前为止提出的代码。除了国防部,我可能还有更多的错误,但我觉得这些错误是国防部误解的结果。我要做的就是在这里获得工作代码(python):

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

正确翻译成MIPS。这是我第一次尝试组装,因此在下面的代码中,可能有超过mod错误使我绊倒:

# 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

Tags: theto代码modl1formain错误
2条回答

您正在查看十六进制的SPIM寄存器。十六进制10是十进制16。

在解决了这些问题之后,下面的代码就像一个符咒。要在MIPS中正确使用mod运算符,必须使用HI和LO。我需要在语句中输入%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

相关问题 更多 >