在此处输入代码我试图计算此数组中可被4整除的元素数,目前它打印出程序循环的次数。由于某种原因,程序每次调用mod。任何人都可以确定为什么会发生这种情况吗?
.data
arr: .word 5, 4, 8,12, 13, 16, 18, 20, 24,23,0
msg: .asciiz "Elements Divisible By 4 : "
four: .word 4
.text
lb $s4, four
.globl main
main:
addi $t0, $0, 0 # clear i
addi $t1, $0, 0 # clear sum
ori $t2, $0, 11 # Initializing t2 to its constant value 10
la $t3, arr # load address of array into t3
loop:
slt $t4, $t0, $t2 # compare, $t4 = i < sum ? 1 : 0
beq $t4, $0, end # if i is not < 11, exit the loop
lw $t4, 0($t3) # load current array element into t4
andi $t4, $t4, 3
beq $t4, $zero, mod
j loop
mod: # if-else exit
add $t1, $t1, 1 # add it to sum
add $t0, $t0, 1 # increment i
add $t3, $t3, 4 # increment current array element pointer
j loop
end:
addi $v0, $0, 4 # Now we print out result: string
la $a0, msg
syscall
addi $v0, $0, 1 # followed by the actual sum (which is in t1)
add $a0, $t1, $0
la $t5, exit
syscall
exit:
j exit
工作版
.data
arr: .word 12, 4, 8, 12, 13, 16, 18, 20, 24, 23, 0
msg: .asciiz "Counter "
fourMod: .word 4
.text
lb $s1, fourMod
.globl main
main:
addi $t0, $0, 0 # clear i
addi $t1, $0, 0 # clear sum
ori $t2, $0, 10 # Initializing t2 to its constant value 10
la $t3, arr # load address of array into t3
loop:
slt $t4, $t0, $t2 # compare, $t4 = i < sum ? 1 : 0
beq $t4, $0, end # if i is not < 10, exit the loop
lw $t4, 0($t3) # load current array element into t4
andi $t4, $t4, 3
beq $t4, $zero, mod
add $t0, $t0, 1 # increment i
add $t3, $t3, 4 # increment current array element pointer
j loop
mod:
#add to the divisible by 4 counter?
add $s2, $s2, 1
add $t0, $t0, 1 # increment i
add $t3, $t3, 4 # increment current array element pointer
j loop
end:
addi $v0, $0, 4 # Now we print out result: string
la $a0, msg
syscall
addi $v0, $0, 1 # followed by the actual sum (which is in t1)
add $a0, $s2, $0
la $t5, exit
syscall
exit:
j exit
答案 0 :(得分:1)
您永远不会告诉您的程序不要在mod:
之后执行代码:
add $t3, $t3, 4 # increment current array element pointer
<--- There's nothing here to prevent the execution to continue with the below add
mod:
add $s2, $s2, 1
如果要跳过某些代码,请使用分支指令。或者在您的情况下,您想要的可能是j loop
。
另一件事是你正在做一个不必要的分工,这通常是一个相对缓慢的操作。检查整数是否为4的倍数可以通过测试两个最低有效位来完成:
andi $t4, $t4, 3 # Isolate the two least significant bits
beq $t4, $zero, mod # We've got a multiple of 4 if those two bits are zero
修改:使用更新的代码,您仍然会在每次迭代时递增“可分割”计数器。如果你颠倒你的分支条件并将代码的这一部分改为:
,那可能是最好的andi $t4, $t4, 3
bne $t4, $zero, not_divisible
add $t1, $t1, 1 # add it to sum
not_divisible: # if-else exit
add $t0, $t0, 1 # increment i
.... # omitted for brevity