MIPS 中的递归三角数程序

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

我正在开发一个 MIPS 程序,该程序接受用户输入并使用递归算法返回一个三角形数。例如,三角形 (4) = 10,三角形 (3) = 6。对于基本情况,三角形 (1) =1。我已经映射了大部分内容,但无论输入如何,我都会收到 1 作为结果,并且不确定我可以做什么来让它工作。

示例算法:

Triangle( N <= 1 ) = 1
o Triangle( N > 1 ) = N + Triangle( N-1 )
o For example:
Triangle( 1 ) = 1
Triangle( 2 ) = 3
Triangle( 3 ) = 6
Triangle( 4 ) = 10

这是我到目前为止所拥有的:

.data
    prompt:     .asciiz "Enter a positive integer (N): "
    result_msg: .asciiz "The triangle number is: "

.text
    main:
        # Prompt user input
        li $v0, 4         #  syscall code for print_str
        la $a0, prompt    # load address of prompt string
        syscall

        # Read user input
        li $v0, 5         # syscall code for read_int
        syscall
        move $s0, $v0     # store input

        # Call recursive subroutine
        move $a0, $s0     # pass N as an argument
        jal triangle

        # Print result
        li $v0, 4         #  syscall code for print_str
        la $a0, result_msg # load address of result_msg string
        syscall

        li $v0, 1         # syscall code for print_int
        move $a0, $v0     # print  result
        syscall

        # Exit
        li $v0, 10        # syscall code for exit
        syscall

    # Recursive subroutine to compute triangle numbers
    triangle:
        # Function prologue
        addi $sp, $sp, -8
        sw $ra, 4($sp)
        sw $a0, 0($sp)

        # Base case: Triangle(1) = 1
        li $t0, 1
        beq $a0, $t0, base_case

        # Recursive case: Triangle(N) = N + Triangle(N-1)
        addi $a0, $a0, -1   # N-1
        jal triangle        # recursive call
        lw $t1, 0($sp)      # retrieve Triangle(N-1) result
        add $v0, $a0, $t1   # N + Triangle(N-1)

        # Function epilogue
        lw $ra, 4($sp)
        lw $a0, 0($sp)
        addi $sp, $sp, 8
        jr $ra

    # Base case subroutine
    base_case:
        li $v0, 1           # return value 1 for base case
        j end_recursive

    # End of recursive subroutine
    end_recursive:
    jr $ra 
recursion assembly mips
1个回答
0
投票

你的基本情况无法清理堆栈——这很糟糕。

要么清理基本情况的堆栈,要么在隔离基本情况之前不要设置堆栈。


虽然没有什么坏处,但在退出时重新加载 $a0 是不合适的,因为调用者不应该期望/依赖它。

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