java 翻译成mips,将Java代码转换为MIPS

I'm suppose to convert this Java code into MIPS. Here's the Java Code:

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

sum = sum + nums[i];}

System.out.println("The average is " + (sum / n));

}

Here's what i have so far:

.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

Somewhere I'm stuck in an infinite loop; I have some problems implementing this line:sum = sum + nums[i]; And i'm suppose to do the division without using the div command.

解决方案

One thing to remember in loops and if statements is you often want to evaluate the branch on the opposite condition. For example your loop should probably look like this:

forLoop:

bge $a1, $s6, endLoop #if i >= n, branch to endLoop

# -- comments are pseudocoded

# something like lw num, $i(nums)

# add sum, sum, num

add $a1, $a1, $a2 #increment i

j forLoop

Division can be handled with some crafty bit shifting and arithmetic. If you can turn this answer into MIPS, I think it will solve your issue there. The solution is in C, but should still be legible.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值