我想把这个Java代码转换成MIPS。这是Java代码:
float data[] = {9.24, 1.15, 3.91, -2.30, 7.43, 5.79, 6.83, 3.14};
int size = 8;
/**
* average is passed the base address of the array of floats and
* its size. It prompts the user for the number of elements from
* the array to average, averages them, and prints the result.
*/
public static void average(float nums[], int size) {
Scanner scan = new Scanner(System.in);
System.out.println("How many should be averaged?");
int n = scan.nextInt();
if (n > size){ // don't average more than there are
n = size;}
float sum = 0.0;
for(int i=0; i<n; i++){
sum = sum + nums[i];}
System.out.println("The average is " + (sum / n));
}
这是我到目前为止所拥有的:
.data
data: .float 9.24, 1.15, 3.91, -2.30, 7.43, 5.79, 6.83, 3.14
size: .word 8
prompt0: .asciiz "\n How many should be averaged? "
prompt1: .asciiz "\n The average is: "
.text
la $s0,data
la $s1,size
lwc1 $f1, 0($s0)
lw $s2, 0($s1)
mtc1 $s2, $f2
cvt.s.w $f2,$f2 #size of array stored in $f2
jal average
average:
la $a0, prompt0
li $v0, 4 #print string
syscall
li $v0, 5 #get float from the keyboard; $f0 now has $v0
syscall
move $s6,$v0
#start comparison
slt $s7,$s6,$s2
beq $s7,$zero, inputGreater
add.s $f5,$f5,$f5 # float sum = 0.0
li $a1, 0 #int i = 0
li $a2, 1 # our incrementor
forLoop:
slt $t0,$a1,$s6 #i < n
add.s $f5,$f5,$f1
add.s $f6,$f6,$f7
j forLoop
endLoop:
la $s5,prompt1
li $v0,4
syscall
div.s $f10,$f5,$f0
li $v0,2
syscall
inputGreater:
#mov.s $f0,$f2
#j forLoop
move $s7,$s2
j forLoop
end:
li $v0,10
syscall
某某地方,我陷入了无限循环;我在实现这一行时遇到了一些问题:sum = sum + nums[i];
而且我想在不使用div
命令的情况下进行除法。
答案 0 :(得分:0)
在循环和if语句中要记住的一件事是你经常想要在相反条件下评估分支。例如,您的循环应该如下所示:
forLoop:
bge $a1, $s6, endLoop #if i >= n, branch to endLoop
#<loop operations> -- comments are pseudocoded
# something like lw num, $i(nums)
# add sum, sum, num
add $a1, $a1, $a2 #increment i
j forLoop
可以通过一些狡猾的位移和算术来处理除法。如果您可以将this answer转换为MIPS,我认为它可以解决您的问题。解决方案是在C中,但仍然应该清晰。