You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将C递归阶乘函数转为MIPS汇编时遇汇编错误求助

Fixing Two MIPS Assembly Errors for Your Factorial Function

Let's walk through fixing those two errors in your MIPS assembly code—they're both common pitfalls when translating C to MIPS, so you're not alone!

Error 1: .ascii directive cannot appear in text segment

You correctly placed your string in the .rdata (read-only data) segment, but two issues are causing this error:

  • You used Chinese quotation marks(“”)instead of standard English quotation marks (""). The assembler can't parse Chinese quotes, so it misinterprets the string definition as invalid text-segment code.
  • While manually adding \000 works, using .asciiz is cleaner—it automatically appends the null terminator required for C-style strings (like the one printf expects).

Error 2: "$L1": operand is of incorrect type

The jr instruction is designed to jump to an address stored in a register (e.g., jr $ra to return to the caller). Since $L1 is a direct label (a fixed memory address), you need to use the j instruction instead, which jumps directly to a label.

Corrected Full MIPS Code

.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: .asciiz "The factorial of 10 is %d\n"

.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
    j $L1 # Jump to code to return (fixed from jr to j)
$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

This code should compile and run correctly, outputting the factorial of 10 as expected.

内容的提问来源于stack exchange,提问作者Fathima Reeza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:34:26