【问题标题】:Convert Java Code to MIPS将 Java 代码转换为 MIPS
【发布时间】:2025-12-02 12:25:01
【问题描述】:

我想将此 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 命令的情况下进行除法。

【问题讨论】:

    标签: mips


    【解决方案1】:

    在循环和 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 语言编写,但仍应清晰可见。

    【讨论】:

      【解决方案2】:

      您必须使用 b(branch) 命令“分支”出循环。 例如: bge:大于或等于的分支。 bgt: 大于的分支 blt:分支小于 ble: 小于等于的分支。

      该命令后跟两个保存数据的寄存器和一个位置。 例如: ble $t0, $t1, endLoop 当 $t0 小于或等于 $t1 时,程序的流程将“被引导”到代码中的 endLoop 位置。

      【讨论】:

        最近更新 更多