MIPS计算器实现减法和加法除法,避免DIV和REM指令 [英] MIPS Calculator implementing division with subtraction and addition, avoiding DIV and REM instructions
本文介绍了MIPS计算器实现减法和加法除法,避免DIV和REM指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用经典的MIPS计算器示例,但正在尝试更改下面的divis(除法)例程,以仅使用加法和减法,而不是MIPS div运算(类似于我对乘法所做的操作)。这可能很容易做到,但我是MIPS的新手,到目前为止我所做的每一次尝试都没有奏效。帮助?
我正在使用qtSpim作为我的模拟器
到目前为止我对组织结构的了解:
start_divis:
add $t1, $zero, $s0 #make copy of first integer value in $s0
add $t2, $zero, $s1 #make copy of second integer value in $s1
add $t0, $zero, $zero #make $t0 the temporary variable to act as a counter
div_loop:
slt $t3, $t2, $t1 #checks if $t1 > $t2
sub $t1, $t1, $t2 #subtract $t2 from $t1
addi $t0, 1 #add one to counter
bne $t3, $zero, div_loop #if first number < second number, loop
end_divis:
move $s5, $t0 #store answer
move $s6, $t1 #store remainder
la $a0, divi_s #get division symbol
move $s7, $a0 #move it to $s7
j div_ans #jump to div_ans
推荐答案
如果您可以使用整数除法(即1/2 = 0
),请考虑以下伪代码:
function multiply(a, b):
sum := 0
for i = 0 to b:
sum := sum + a
return sum
function divide(a,b):
count := 0
while a ≥ b:
a := a - b
count := count + 1
return count
您所写的内容有几处错误:
第一行
slt $t3, $t2, $t1 #checks if $t1 > $t2
不正确。否定>的正确方法是使用≤。这意味着该行应更改为:
sle $t3, $t2, $t1 #checks if $t1 > $t2
接下来,循环的条件在顶部,而使用它的实际分支在底部。您应该知道,While循环始终检查顶部的条件。
考虑:
div_loop:
sle $t3, $t2, $t1 #checks if $t1 > $t2
beq $t3, $zero, end_divis #if first number < second number, break
sub $t1, $t1, $t2 #subtract $t2 from $t1
addi $t0, 1 #add one to counter
j div_loop #loop
这篇关于MIPS计算器实现减法和加法除法,避免DIV和REM指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文