Convert Java Code to MIPS

2019-06-05 09:17发布

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<n; 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.

标签: mips
1条回答
可以哭但决不认输i
2楼-- · 2019-06-05 09:36

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
         #<loop operations> -- 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.

查看更多
登录 后发表回答