MIPS汇编while循环

时间:2018-12-05 15:43:19

标签: java assembly mips

我目前正在学习MIPS,在做一些练习时,我遇到了一个练习,即首先用Java编写斐波那契序列,然后将其转换为MIPS Assembly。我只能使用beqbneslt 我的Java代码如下:

    int n = 50; F_MAX  v
    int t1 = 0;
    int t2 = 1;
    int sum = 0;
    while(t1 <= n)
    {
      System.out.print(t1 + " ")
      sum = t1 + t2
      t1 = t2
      t2 = sum;
     }

意思是如果n = 50,则应打印50之前的所有数字(0; 1; 1; 2; 3; 5; 8; 13; 21; 34)

我的MIPS汇编代码为:

      la $s0, F_MAX
      lw $s0, 0($s0)         #$s0 = int n = F_MAX (50);



  addi  $t1, $zero, 0     # $t1 = int t1 = 0;
  addi  $t2, $zero, 1     # $t2 = int t2 = 1;
  addi  $t3, $zero, 0     # $t3 = int sum = 0


  while:

        beq $t1, $s0, Exit  #if t1 == 50 exit the program

        addi $v0, $zero, 1      # syscall code to print integer
        add $a0, $zero, $t1     # t1 to be printed
        syscall                 # print t1

        add $t3, $t1, $t2
        addi $t1, $t2, 0
        addi $t2, $t3, 0

        addi  $v0, $zero, 4     # syscall code to print a string
        la  $a0, COMMA
        syscall                 # print a comma (and a space)


        j while

Exit:
li $v0, 10
syscall

但是由于某种原因,它使我溢出并打印所有可能的正数,但我不知道为什么。

1 个答案:

答案 0 :(得分:0)

所以这是更新的代码: 由于从未满足过t1 == 50的条件,因此alwasys是错误的,因此我不得不使用sltbne指令。

     la $s0, F_MAX
     lw $s0, 0($s0)                    #$s0 = int n = F_MAX (50);



     addi  $t1, $zero, 0               # $t1 = int t1 = 0;
     addi  $t2, $zero, 1               # $t2 = int t2 = 1;
     addi  $t3, $zero, 0               # $t3 = int sum = 0


           while:



           addi $v0, $zero, 1           # syscall code to print integer
           add $a0, $zero, $t1          # t1 to be printed
           syscall                      # print t1

           add $t3, $t1, $t2
           addi $t1, $t2, 0
           addi $t2, $t3, 0

           addi  $v0, $zero, 4          # syscall code to print a string
           la  $a0, COMMA
           syscall                      # print a comma (and a space)

           slt $t4, $t1, $s0            #if t1 < 50 $t4 = 1
           bne $t4, $zero, while        #if $t4 != $zero goto while

           slt $t4, $s0, $t1            #if 50 < $t1 $t4 = 1
           bne $t4, $zero, Exit         #if $t4 != $zero goto Exit

  Exit:
  li $v0, 10
  syscall