【问题标题】:MIPS, using a while loop to calculatethe sum of odd integers 1-9MIPS,使用while循环计算奇数1-9之和
【发布时间】: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


【解决方案1】:
la $t1, num

您显然在这里遇到了麻烦,因为您每次进行系统调用时都会用num 的地址覆盖您的累加器。您每次都会丢失当前的计算状态。

您需要保存您的寄存器,或者只是使用不同的寄存器。由于我不知道您使用的是什么操作系统,因此我不知道您是否更普遍地需要通过系统调用保存寄存器,但这也可能是错误的来源。

【讨论】:

    【解决方案2】:

    我在建筑课上做过类似的问题,这似乎是所有学生中经常出现的问题。当遇到与此类似的问题时,我们教授的建议是使用不同的寄存器来临时存储寄存器的地址,以避免覆盖我们最常用的寄存器中的其他所需值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-29
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多