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

Java转MIPS汇编循环程序问题:仅打印首条消息,后续输出缺失

MIPS汇编程序无法输出结果的问题修复

我需要将一段统计数字中10的个数及余数的Java代码转换为MIPS汇编代码,但自行编写的汇编程序仅能打印输入提示消息,后续两条结果消息及对应数值均无法输出。以下是原Java代码和我写的MIPS汇编代码:

原Java代码

/**
 * 统计给定数字中包含多少个10,并返回小于10的余数
 */
Scanner input = new Scanner(System.in);
System.out.println("enter num: "); // 打印输入提示
int num = input.nextInt(); // 获取用户输入
int numOf10 = 0; // 计数器
while(num > 9) { // 循环开始
    num -= 10; // 从输入数字中减去10
    numOf10++; // 计数器加1
}
System.out.println("number of 10 is: " + numOf10); // 输出10的个数
System.out.println("the remain: " + num); // 输出余数

我编写的MIPS汇编代码(存在问题)

.data
EnterMessage: .asciiz"Enter the number:\n "
ResultMessage: .asciiz"number of 10 is:\n"
remainMessage: .asciiz"the remain:\n "

.text

main:
#ask user to enter input 
li $v0,4
la $a0,EnterMessage
syscall

#read user input
li $v0,5
syscall

#save input
move $t0,$v0

#creat variables
#$t2=9
addi $t2,$zero,9
#counter=$t3=0
addi $t3,$zero,0
#jal loop

#while loop
loop:
ble $t1,$t2,exit

subi $t0,$t0,10
addi $t3,$t3,1
j loop

print:

#print ResultMessage num
li $v0,1
move $a0,$t3
syscall

#print ResultMessage
li $v0,4
la $a0,ResultMessage
syscall

#print remainMessage num
li $v0,1
move $a0,$t0
syscall

#print remainMessage 
li $v0,4
la $a0,remainMessage 
syscall

#close the program
exit:

#end 
li $v0,10
syscall

问题分析与修复

你的汇编程序有几个关键错误导致无法输出结果:

  • 循环判断变量错误:循环条件里用了未赋值的$t1,正确应该用存储输入值的$t0和代表9的$t2比较。
  • 循环退出跳转错误:原代码循环退出时直接跳exit(程序结束),跳过了结果打印逻辑,应该跳print标签执行输出。
  • 打印顺序颠倒:原代码先打印数值再打印提示消息,和Java逻辑相反,应该先输出提示文本,再输出对应数值。
  • 标签位置错误:exit标签应该放在打印逻辑之后,确保输出完成后再结束程序。

修复后的MIPS汇编代码

.data
EnterMessage: .asciiz "Enter the number:\n"
ResultMessage: .asciiz "number of 10 is: "
remainMessage: .asciiz "the remain: "

.text
main:
    # 打印输入提示
    li $v0, 4
    la $a0, EnterMessage
    syscall

    # 读取用户输入
    li $v0, 5
    syscall
    move $t0, $v0  # $t0存储输入的数字

    # 初始化变量:$t2=9(循环终止阈值),$t3=0(计数器)
    addi $t2, $zero, 9
    addi $t3, $zero, 0

# while(num > 9) 循环
loop:
    ble $t0, $t2, print  # 当num<=9时,跳转到打印逻辑
    subi $t0, $t0, 10    # num = num -10
    addi $t3, $t3, 1     # 计数器加1
    j loop               # 回到循环开头

# 打印结果逻辑
print:
    # 打印"number of 10 is: "
    li $v0, 4
    la $a0, ResultMessage
    syscall
    # 打印计数器数值
    li $v0, 1
    move $a0, $t3
    syscall
    # 换行
    li $v0, 4
    la $a0, '\n'
    syscall

    # 打印"the remain: "
    li $v0, 4
    la $a0, remainMessage
    syscall
    # 打印余数
    li $v0, 1
    move $a0, $t0
    syscall
    # 换行
    li $v0, 4
    la $a0, '\n'
    syscall

# 结束程序
exit:
    li $v0, 10
    syscall

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:50:41