如何计算MIPS中奇数正整数的总和?我在家里有一个MIPS模拟器,我用来预订以帮助验证我的工作。我的大学有一个计算机实验室,其硬件由外部公司提供。我想这个想法是,大学通过课程“向学生提供硬件”。对我来说问题的部分原因是我想在学校使用电路板时验证我的代码是否正常工作,但验证代码在家工作似乎更容易。无论如何,我认为代码应该是这样的:
andi $t8, $s0, 1 #value from $s0 and add 1 to it. Place in $t8 register
bnez $t8 #This should determine if its odd
beqz $79 #This should determine if its even
even:
addi $t7, $t8, -1
bnez $t7, odd
odd:
addi $t6, $t7, -2
Rt6, loop
有更简单的方法吗?我需要编写一个主例程,在执行结束时执行v0
= 1
和1000
之间的奇数正整数之和。在这种情况下,$t8
是我的$v0
。任何有用的建议都会被认真考虑。
答案 0 :(得分:0)
这是一些带注释的代码,用于处理奇数和偶数值的总和。它还有一个子程序的例子。
.data
array:
.word 17767, 9158, 39017, 18547
.word 56401, 23807, 37962, 22764
.word 7977, 31949, 22714, 55211
.word 16882, 7931, 43491, 57670
.word 124, 25282, 2132, 10232
.word 8987, 59880, 52711, 17293
.word 3958, 9562, 63790, 29283
.word 49715, 55199, 50377, 1946
.word 64358, 23858, 20493, 55223
.word 47665, 58456, 12451, 55642
arrend:
msg_odd: .asciiz "The sum of the odd numbers is: "
msg_even: .asciiz "The sum of the even numbers is: "
msg_nl: .asciiz "\n"
.text
.globl main
# main -- main program
#
# registers:
# t0 -- even sum
# t1 -- odd sum
# t2 -- current array value
# t3 -- isolation for even/odd bit
# t6 -- array pointer
# t7 -- array end pointer
main:
li $t0,0 # zero out even sum
li $t1,0 # zero out odd sum
la $t6,array # address of array start
la $t7,arrend # address of array end
main_loop:
bge $t6,$t7,main_done # are we done? if yes, fly
lw $t2,0($t6) # get value
addiu $t6,$t6,4 # point to next array element
andi $t3,$t2,1 # isolate LSB
beqz $t3,main_even # is is even? if yes, fly
add $t1,$t1,$t2 # add to odd sum
j main_loop
main_even:
add $t0,$t0,$t2 # add to even sum
j main_loop
main_done:
# output the even sum
la $a0,msg_even
move $a1,$t0
jal print
# output the odd sum
la $a0,msg_odd
move $a1,$t1
jal print
# terminate program
li $v0,10
syscall
# print -- output a number
#
# arguments:
# a0 -- pointer to message
# a1 -- number to output
print:
# output the message
la $v0,4
syscall
# output the number
li $v0,1
move $a0,$a1
syscall
# output a newline
la $a0,msg_nl
li $v0,4
syscall
jr $ra # return
如果您想要根据自己的经验编写关于编写干净的asm的一些提示,请参阅我的回答:MIPS linked list
我已将spim
,QtSpim
和mars
用于模拟器。就个人而言,我更倾向于mars
。请参阅:http://courses.missouristate.edu/KenVollmar/mars/