问题描述
嘿,我究竟能找到使用MIPS汇编整数的平方根?
hey how exactly can I find the square root of an integer using MIPS assembly?
推荐答案
我们可以像使用提交的的,并根据需要修改它。进入MIPS之前,让我们来看看用C实现:
We can use an algorithm like the one submitted for this question and adapt it as needed. Before getting into MIPS, lets look at an implementation in C:
//Function to compute sqroot(n)
int sqroot(int n) {
int x = n;
for (int i = 0; i < (n/2); i++)
x = (x + n / x) / 2;
return x;
}
的 sqroot(N)
函数计算,相等于 N
的平方根的地板整数。所以,如果你要调用 sqroot(225)
你会得到15不如预期,但 sqroot(15)
将返回3,而不是3.87298。
The sqroot(n)
function will compute and integer equivalent to the floor of the square root of n
. So if you were to call sqroot(225)
you would get 15 as expected, but sqroot(15)
would return 3 instead of 3.87298.
从C code,我们可以勾勒出MIPS code将是什么样子:
From the C code, we can outline what the MIPS code will look like:
In calling function:
Load the number to be squared into $a0
jal root
root:
Initialize $t0 = n, $t1 = i = 0, $t2 = x = n = $a0, $t3 = n/2
Loop:
Divide n/x
Add x to n/x
Divide (x + n/x) by 2
Check if $t1 < $t3
If it is, branch back to loop
Else, move x into return register $v0
请注意:
- 一定要推,并根据需要弹出堆栈。我离开是出于对简单性。
- 当2的功率分配,可以使用SRL指令。
- 有关澄清和说明MIPS的更多信息,请。
- Be sure to Push and Pop the stack as needed. I left that out for simplicity.
- When dividing by a power of 2, you can use the srl instruction.
- For clarification and additional information on MIPS instructions, click here.
这篇关于查找有关MIPS汇编整数的平方根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!