使用递归打印数字平方的MIPS程序

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

我的目标是编写一个 MIPS 汇编程序,生成整数 N 的平方,该整数等于 Triangle( N ) + Triangle( N-1 )。三角形函数定义为 Triangle( N <= 1 ) = 1 and Triangle( N > 1 ) = N + Triangle( N-1 )。必须使用递归(非叶)过程

This is the code so far: 

# Recursive function to calculate the square of N

# Square( N ) = Triangle( N ) + Triangle( N - 1 )

.text

.globl main

main:

   li $v0, 4                   # Prompt user for input

   la $a0, prompt              # Load address of prompt string

   syscall

   li $v0, 5                   # Read user input

   syscall

   move $t0, $v0               # Store user input in $t0

   jal Square                  # Call Square function

   move $a0, $v0               # Move result to $a0 for printing

   li $v0, 1                   # Print the result

   syscall

   li $v0, 10                  # Exit

   syscall

Square:

   addi $sp, $sp, -8           # Create stack frame

   sw $ra, 0($sp)              # Save return address

   sw $a0, 4($sp)              # Save argument N

   li $v0, 1                   # Base case: Square( N <= 1 ) = 1

   blez $a0, square_end        # Return 1 if N <= 1

   addi $a0, $a0, -1           # Calculate N - 1

   jal Triangle                # Call Triangle( N - 1 )

   move $t0, $v0               # Store result in $t0

   lw $a0, 4($sp)              # Retrieve original N

   jal Triangle                # Call Triangle( N )

   addu $v0, $v0, $t0          # Add results for Square( N )

square_end:

   lw $ra, 0($sp)              # Restore return address

   addi $sp, $sp, 8            # Restore stack pointer

   jr $ra                      # Return

Triangle:

   # Implementation of Triangle function

我走在正确的道路上吗?

assembly mips mars-simulator
1个回答
0
投票

如果您尝试遵循标准调用约定(好主意),那么您就走在正确的道路上。

但是,

$t0
不会在递归函数调用中幸存(不一定是因为递归)。

因此,不要使用寄存器来存储中间值,而是使用另一个堆栈位置。

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