【问题标题】:How to convert this code to MIPS?如何将此代码转换为 MIPS?
【发布时间】:2015-10-05 00:18:44
【问题描述】:

C++ 代码:

#include <iostream>
using namespace std;

int main()
{
    int num;
    int sum = 0;

    cout << " Enter a number : ";
    cin >> num;

    while ( num > 0 ) {
    sum += num % 10;
    num /= 10;
}

如何将其转换为 MIPS?

我知道,我可以使用 $HI$LO 寄存器,但我无法实现。

.data 
error: .asciiz "The Number you entered is not valid"
input: .asciiz "Please enter a number"

.text 

main:
#GET NUMBER FROM USER
li $v0, 4 #load syscall print string
la $a0, input  #load adress of str1 into $a0
syscall   #make the syscall

#SAVE NUMBER
li $v0, 5 #load syscall read_int into $v0
syscall   #make the syscall
move $s0, $v0 #move the number read into $t0 now $t0=n

#make sure number is between 100 and 400
addi $t1, $zero, 400
addi $t2, $zero, 100 
ble $s0, $t2, EXIT 
bge $s0, $t1, EXIT 



loop: 
div $s0, $s1 
add $s2, $s2, $LO 
add $s0, $HI, $zero 
bgt $s0, $zero, loop 




end: 
li $v0, 10 
syscall


EXIT: 
li $v0, 4 #load syscall print string
la $a0, error  #load adress of error into $a0
syscall   #make the syscall

【问题讨论】:

  • 请提供您尝试过的内容。
  • 好吧,就像我说的 MIPS 新手,所以我的尝试是徒劳的。所以输入的数字必须在 100 到 400 之间。这是我尝试过的,但我卡在 L1
  • 失败尝试没有错。如果你有所有的成功尝试,那你为什么要在这里问一些事情呢?只要确保你已经尝试过。

标签: mips


【解决方案1】:

当你在 MIPS 中做 div 时,商进入$HI,余数进入$LO。如果 while 循环是您遇到的问题,那应该会有所帮助。

Sum: s2
Num: s0
10: s1

While:      # while num >0
div $s0, $s1. #  $s0/$s1    num/10
add $s2, $s2, $LO # sum += num%10
add $s0, $HI, $zero   # num /= 10
bgt $s0, $zero, While # if num >0 loop again

剩下的只是一个分支大于的循环。

【讨论】:

  • 是否要检查大于的分支以确保 $HI 大于 0?
  • 应该检查你的num保存的寄存器是否在它存储之后,所以它会检查它是否大于零,如果是则跳回循环
  • 好吧,是的,由于某种原因,我很难理解这个问题
  • 没毛病,有些概念一开始很难理解
  • 让我重新编辑上面的代码,看看我们是否可以从那里开始
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-01
  • 2023-03-20
  • 2012-06-16
  • 2010-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多