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

C代码与对应MIPS汇编代码逻辑不一致,求问题排查

问题排查与修正

对比C代码和你的MIPS汇编逻辑,核心错误出在循环分支的流程处理上:

错误点分析

C代码的while循环逻辑是:

  1. 判断当前指针指向的元素是否为0,是则退出循环
  2. 如果元素小于10,累加进total
  3. 无论是否累加,都要将指针后移一位,回到循环开头

但你的汇编代码中:

  • 当元素小于10进入update分支后,只执行了累加操作,没有移动指针,也没有回到循环,直接跳转到done结束了整个循环,导致数组中后续的元素(比如4、6、2)完全没被处理。
  • 只有当元素不小于10时,才移动指针并回到循环,这和C代码的逻辑完全不一致。

修正后的汇编代码

.data
x:  
    .word 3, 10, 4, 25, 33, 6, 2, 0
text:
    .asciiz "The total of things less than 10 is "
newline:
    .asciiz "\n"

    .text
main: 
    li $t0, 0          # total = 0
    la $t1, x          # pointer = &x[0]
    li $t3, 10         # t3 = 10
loop_start:
    lw $t2, 0($t1)     # t2 = *pointer
    beq $t2, $0, done  # if *pointer == 0, exit loop
    
    blt $t2, $t3, update_total  # if *pointer <10, go to update
    j move_pointer              # else, skip to move pointer

update_total:
    add $t0, $t0, $t2  # total += *pointer

move_pointer:
    addi $t1, $t1, 4   # pointer++ (每个int占4字节)
    j loop_start        # 回到循环开头

done:
    # 输出结果
    la $a0, text
    li $v0, 4
    syscall

    move $a0, $t0
    li $v0, 1
    syscall

    la $a0, newline
    li $v0, 4
    syscall

    li $v0, 10
    syscall

修正说明

  1. 新增move_pointer分支,专门处理指针后移和循环跳转,确保无论是否累加total,都会执行指针移动并回到循环,和C代码逻辑对齐。
  2. 调整循环标签为loop_start(仅为可读性优化),将原有的分支逻辑拆分,避免流程混乱。
  3. 修正后,代码会遍历数组直到遇到0,正确累加所有小于10的元素,最终输出结果为The total of things less than 10 is 15。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:30:46