【发布时间】:2014-02-11 23:26:42
【问题描述】:
以下是我在 MIPS 中使用 while 循环计算奇数和的代码。
.data
num: .space 4
.text
.globl main
main:
li $t1, 1
li $t2, 9 # make $t2 9 to break the loop
li $t3, 1
loop:
beq $t3, 11, Exit # check to see if $t3 = 11 if so exit
addi $t3, $t3, 2 # change $t3 to next odd number by adding 2
add $t1, $t1, $t3 # add $t3 to $t1 (1+3,...3+5...etc...)
j loop #jump back to the start of the loop
Exit:
li $v0, 1 # system call code to print an int
lw $a0, num # address of int to print
syscall # print the int
jr $ra #exit
这是我第一次真正体验 MIPS,我不确定这段代码出了什么问题。我将 print 放在 while 循环中以查看它是否曾经计算过,但结果始终为 1。 所以,我最后的结果是 111111。
编辑:删除循环内的打印结果相同。
操作系统是 Windows 7 64x
更新:将 num 作为变量会使事情变得过于复杂。代码已修改如下并且可以正常工作。感谢您的帮助!
enter code here
.data
.text
.globl main
main:
addi $t1, $0, 1
addi $t2, $0, 3
loop: bge $t2, 11, Exit # check to see if $t3 >= 11 if so exit
add $t1, $t1, $t2 # add $t2 to $t1 (1+3,...3+5...etc...)
addi $t2, $t2, 2 # change $t2 to next odd number by adding 2
j loop #jump back to the start of the loop
Exit:
li $v0, 1 # system call code to print an int
move $a0,$t1 # address of int to print
syscall # print the int
jr $ra #exit
【问题讨论】:
-
什么操作系统?
-
如果从循环中删除打印,它的行为是否会改变?
-
您正在打印存储在
num的值,但我看不到您曾经向num写过任何内容。
标签: mips