MIPS,使用while循环来计算1-9的奇数整数之和

问题描述 投票:0回答:2

以下是我在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的真实经验,我不确定这段代码出了什么问题。我将打印内容放入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
mips
2个回答
1
投票
la $t1, num

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

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.