You need to enable JavaScript to run this app. MIPS汇编整数数组求和循环异常 结果错误该如何修复
优惠活动
大模型
产品
解决方案
定价
更多

MIPS汇编整数数组求和循环异常 结果错误该如何修复

MIPS整数数组求和代码修复

问题根因

你当前代码的错误出在数组元素加载指令使用错误:你用了lb(加载字节指令)读取32位整数(.word类型占4字节内存),每次只会读取每个数组元素的最低1字节,导致数值读取完全错误,累加结果不符合预期。

修复方案

仅需要修改int_array_sum函数内的元素加载指令,将lb $t3, 0($t2)替换为lw $t3, 0($t2)即可,lw是加载字指令,刚好对应读取32位整数的需求,修改不会触碰禁止改动的代码段。

修正后的完整可运行函数代码如下:

int_array_sum:
    li  $v0, 0
    li  $t0, 0
loopA:
    #If $t0 (i) is = $a1 skip to end_int
    beq $t0, $a1, end_int   # Done if i == N
    
    # Multiply $t0 by 4 and store it in $t1
    sll $t1, $t0, 2     # Indexadr = i * 4
    
    #Add $t1 with $a0 and save in $t2 
    add $t2, $t1, $a0       # Address = $a0 + Indexadr  
    
    #Retrieve the number from memory that $t2 points to and store in $t3
    lw $t3, 0($t2)          # 修复点:将lb改为lw,加载完整32位整数
    
    #Add $t3 to $v0 (results register)
    addu $v0, $v0, $t3      # Sum = Sum + n
    
    #Add 1 to register $t0
    add $t0, $t0, 1         # i = i + 1
    
    #Repeat
    j loopA
end_int:
        jr      $ra      # Return to calling code

修改后运行即可得到预期输出Sum of the 11 integer is 217。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 04:21:01