【问题标题】:from java to MIPS assembly for a simple while loop [closed]从 java 到 MIPS 程序集的简单 while 循环
【发布时间】:2023-01-26 22:26:22
【问题描述】:

我需要将代码从 java 转换为程序集,但它只打印第一条消息。但是最后两条消息既不打印消息也不打印结果的数字。 java和assembly中的两段代码是我写的如下:

java中的代码:

    /**
     * this program count how many 10s can be in a givin number the return the extra or the remain that less than 10
     */
    Scanner input=new Scanner(System.in);
    System.out.println("enter num: ");//print input message
    int num=input.nextInt();// user input 
    int numOf10=0;//counter 
    while(num>9){ //start of while loop
        num-=10;//subtruct 10 from the input number
        numOf10++;//add one to the counter 
       
    }
    System.out.println("number of 10 is: "+numOf10);//print message contain 
    System.out.println("the remain: "+num);//print message contain 

//////////////////////////////////////////////////////////////////////////////////// the code in assembly:

.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

【问题讨论】:

  • 尝试调试它。

标签: loops assembly while-loop mips


【解决方案1】:

你的问题在这里:

ble $t1,$t2,exit

这里有几个问题。首先,exit 导致:

#close the program
exit:

#end 
li $v0,10
syscall

所以你什么都没做就跳到了最后。

其次,您已选择 $t1 作为您从未设置过的比较寄存器之一。所以它的值目前是未知的(很可能是内核或操作系统或任何在 main 之前将所有寄存器归零的东西,但假设那个不是一个好习惯。)

让我们考虑一下被问到的问题:

 while(num>9){ //start of while loop
        num-=10;//subtruct 10 from the input number
        numOf10++;//add one to the counter 
       
    }

将高级语言翻译成汇编时,我们不必按照源语言编写的方式来做所有事情。就goto而言,我们可以将其视为:

loop_begin:
   if (num > 9) goto loop_exit;
   num -= 10;
   numOf10++;
   goto loop_begin;
loop_exit:

在大多数情况下,您的想法是正确的。 MIPS 的好处是分支语法不像其他汇编语言那样迟钝,因为您不必记住进位清除是表示小于还是大于等。

loop:
ble $t0,$t2,print  # if $t0 (num) > 9 goto print
subi $t0,$t0,10    # num = num - 10
addi $t3,$t3,1     # counter++
j loop             # goto loop

【讨论】:

  • 您需要反转/否定 C if-goto-label 和汇编版本中的循环退出测试条件与 while 结构化语句形式的循环继续条件。
  • 呸!在这里我说的是 MIPS 如何更容易分支。看来我有点生疏了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
  • 1970-01-01
  • 1970-01-01
  • 2015-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多