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

MIPS,使用while循环计算奇数整数的和1-9,mips,Mips,下面是我在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

下面是我在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

编辑:删除循环内部的打印,结果相同

操作系统是Windows764X

更新:将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
的值,但我看不到您向
num
写入任何内容。
la $t1, num