MIPS:比较两个数组的第一个元素

时间:2013-10-26 21:05:07

标签: arrays mips

function:


la $s0, array1      # loads address of array1 into $s0
lw $t8, ($s0)       # loads word contained in $s0 into $t8

la $s1, array2      # loads address of array2 into $s1
lw $t9, ($s1)       # loads word contained in $s1 into $t9

beq $t8, $t9, count # if first element of arrays is equal --> count
j end

count: 

la $t7, counter     # loads address of count into $t7
lw $t3, ($t7)       # loads word contained in $t7 into $t3
addi $t3, $t3, 1    # increments count by 1
sw $t3, counter     # now count var contains 1


printcount: 

li $v0, 4               # print string syscall code  
la $a0, prompt3     # prints "number of same elements: "
syscall

la $t6, counter     # loads address of count into $t6
lw $t5, ($t6)       # loads word contained in $t6 into $t5
li $v0, 1               # print integer syscall code
move $a0, $t5       # move integer to be printed into $a0
syscall


end:

    li $v0, 10          # system code halt
syscall

嗨,程序的这一部分应该比较两个数组的第一个元素(用户输入的,我已经确认数组存储正确),如果这些元素相等,'counter'将增加1,并打印,以便我知道它是否正常工作。

问题在于它总是打印'1',无论两个元素是否相等。可能导致这种情况的原因是什么?

1 个答案:

答案 0 :(得分:0)

好吧,代码最终执行标签count处的指令,无论是否采用分支。尝试bne而不是beq

bne $t8, $t9, skip_count # if first element of arrays not equal --> skip_count


count: 

la $t7, counter     # loads address of count into $t7
lw $t3, ($t7)       # loads word contained in $t7 into $t3
addi $t3, $t3, 1    # increments count by 1
sw $t3, counter     # now count var contains 1

skip_count:
相关问题