我目前正在编写一个执行阶乘的mips程序。我在java中编写了factorial示例,并且在java代码下面也有MIPS程序。我已经写出了大部分MIPS,但我很困惑为什么它没有正确处理。任何提示将不胜感激。
Java code for the iteratve factorial algorithm:
import java.util.Scanner;
public class FactorMachine {
public static void main(String[] args) {
int input;
Scanner in = new Scanner(System.in);
System.out.println("Enter an integer to be factored: ");
input = in.nextInt();
{
int x, factorial = 1;
for (x = input; x > 1; x--)
factorial *= x;
System.out.println("Factorial #" + input + " is " + factorial);
}
}
}
MIPS代码:
.data
p1: .asciiz "Enter an integer to be factored: "
ans1: .asciiz "Factorial # "
ans2: .asciiz " is "
ans3: .asciiz "\n\n"
.text
.globl main
main: li $v0, 4
la $a0, p1
syscall
li $v0, 5
syscall
move $t0, $v0 #this is input
li $t1, 1 #initilize factorial
move $t2, $t0 #initilize x
loop:
blt $t2, 1, done
sub $t2, $t2, 1
mul $t3, $t1, $t0
j loop
done:
li $v0, 4
la $a0, ans1
syscall
li $v0, 1
move $a0, $t3
syscall
jr $ra
答案 0 :(得分:1)
让我们看一下Java代码的作用(为了清楚起见,我将X *= Y
更改为X = X * Y
):
for (x = input; x > 1; x--)
factorial = factorial * x;
现在让我们来看看你的汇编代码:
move $t2, $t0 #initilize x
loop:
blt $t2, 1, done
sub $t2, $t2, 1
mul $t3, $t1, $t0
j loop
以及与Java相对应的内容:
for (x = input; x >= 1; ) {
x--;
temp = factorial * input;
}
注意区别?你'再:
x
,而不是像在原始Java代码中那样递减。input
($t0
)而不是x
($t2
)。factorial
($t1
)。因此,您始终会获得1 * input
的产品,当然等于input
。