【问题标题】:Finding factorial of a number using recursive call in MIPS programming在 MIPS 编程中使用递归调用查找数字的阶乘
【发布时间】:2019-11-09 04:20:39
【问题描述】:

这是C源代码

#include <stdio.h>

int main() {
    
    printf("The Factorial of 10 is %d\n", fact(10));
}

int fact(int n) {

    if (n < 1)
        return (1);
    else
        return (n * fact(n - 1));
}

我正在将 C 编程函数转换为 MIPS,但是当我运行 MIPS 程序时,我收到 .ascii 部分的错误。

    .text
    .globl main
main:
    subu    $sp,$sp,32  # Stack frame is 32 bytes long
    sw  $ra,20($sp)     # Save return address
    sw  $fp,16($sp)     # Save old frame pointer
    addiu   $fp,$sp,28  # Set up frame pointer

    li  $a0,10      # Put argument (10) in $a0
    jal     fact        # Call factorial function
    la  $a0,$LC     # Put format string in $a0
    move    $a1,$v0     # Move fact result to $a1
    jal     printf      # Call the print function

    lw  $ra,20($sp)     # Restore return address
    lw  $fp,16($sp)     # Restore frame pointer
    addiu   $sp,$sp,32  # Pop stack frame
    jr  $ra         # Return to caller
    
    .rdata
$LC:
    .ascii “The factorial of 10 is %d\n\000”

    .text
fact:
    subu    $sp,$sp,32  # Stack frame is 32 bytes long
    sw  $ra,20($sp)     # Save return address
    sw  $fp,16($sp)     # Save frame pointer
    addiu   $fp,$sp,28  # Set up frame pointer
    sw  $a0,0($fp)  # Save argument (n) to use for Recursive Call
    
    lw  $v0,0($fp)  # Load n
    bgtz    $v0,$L2     # Branch if n > 0
    li  $v0,1       # Return 1
    jr  $L1         # Jump to code to return
$L2:
    lw  $v1,0($fp)  # Load n
    subu    $v0,$v1,1   # Compute n - 1
    move    $a0,$v0     # Move value to $a0
    
    jal     fact        # Call factorial function
    lw  $v1,0($fp)  # Load n
    mul     $v0,$v0,$v1     # Compute fact(n-1) * n
    
$L1:                # Result is in $v0
    lw  $ra, 20($sp)    # Restore $ra
    lw  $fp, 16($sp)    # Restore $fp
    addiu   $sp, $sp, 32    # Pop stack
    jr  $ra         # Return to caller

.ascii 代码部分给我一个错误,说它不应该在 .text 中:

“.ascii”指令中的错误不能出现在文本段中

这也是说:

“$L1”:操作数的类型不正确

【问题讨论】:

  • jr 进行注册。使用j L1进行正常的直接跳转。

标签: c assembly mips mars-simulator


【解决方案1】:

.ascii 代码部分给我一个错误,说它不应该在 .text 中:

“.ascii”指令中的错误不能出现在文本段中”

我在这里很危险,因为我不能 100% 确定你在运行什么,但是像 MARS 之类的一些 sim 无法识别 rdata 段。您可以尝试只使用.data

另外,如果您使用的是 WinMIPS64 之类的东西,您可能想尝试将 .data 段放在代码的顶部。我了解您的操作在某些环境中是正确的,但在其他环境中不起作用,因此请试一试。

我建议你单独尝试这些东西,以防万一。

【讨论】:

  • 感谢您的帮助!我确实尝试使用 .data 将 ascii 一直放在顶部,并且成功了
  • 太棒了!如果我的答案对您有用或有用,您可以投票或接受它作为答案吗?参考:stackoverflow.com/help/someone-answers
猜你喜欢
  • 2021-12-06
  • 2021-09-02
  • 1970-01-01
  • 2019-10-22
  • 2013-09-18
  • 2012-01-01
  • 1970-01-01
  • 2018-03-07
  • 2018-06-08
相关资源
最近更新 更多