将C代码转换为MIPS汇编

时间:2014-10-15 03:19:36

标签: loops assembly mips

在本练习中,编写一个完整的MIPS汇编语言程序,提示用户输入正整数 n并计算并显示前n个正整数的平方和。

。这是程序的伪代码,

给定的C代码是:

Function main()
Integer i, n, sum
PrintString("Enter an integer (> 0): ")
n = ReadInt()
For (i = 1, sum = 0; i <= n; ++i)
sum += i * i
End For
PrintString("The sum of the squares of the first ")
PrintInt(n)
PrintString(" positive integers is ")
PrintInt(sum)
Exit()
End Function main

到目前为止,我在大会上有这个:

.data
# Strings that will be printed in program
 i:  .word 0  # integer i;
 n: .word 0 # integer n;
 sum: .word 0 #integer sum;
 prompt:    .asciiz  " Enter an integer(> 0:\n" "   # char *s_age = Enter an integer"
 sum:     .asciiz   "The sum of the squares of the first"  # char *s_color = "is odd? "

#=========================================================================================================
# TEXT
#=========================================================================================================
     .text
     main: 

     la $t0,prompt  #Prompt user to enter integer as input
     li $v0, 4 # Loads the immediate/constant(4)into register $v0 the opcode to print string
    syscall 

    li $v0,5  # Loads the immediate/constant(5) into register $v0 the opcode to read integer
    syscall
      move $t0, $v0 
       li $t0, n # t0 is a constant 10
  li $t1, 0 # t1 stores  counter (i)
    loop: 
    bgt $t1,$t0,exit # Use branch greater than to implement the for loop,  with  n ( stored in register $t1) as termination condition 
    addi $a0,$a0,1
    mul  $a1,$v0,i
     j loop  
     exit: 

2 个答案:

答案 0 :(得分:0)

我还没有测试过这段代码(目前我没有MIPS机器/模拟器),但我认为它应该可行:

.data
    result: .word 0
    prompt1: .asciiz "Enter an integer: "
    prompt2: .asciiz "The sum of the squares is: "


.text
    main:
        #Show "Enter an integer: " message.
        la $a0, prompt1
        li $v0, 4
        syscall

        #Read integer and store at $t2.
        li $v0, 5
        syscall
        move $t2, $v0

        #Prepare some temporal registers.
        li $t0, 0 #sum = 0;
        li $t1, 1 #i = 1;

    loop:
        mul $t3, $t1, $t1 #temp = i*i;
        add $t0, $t0, $t3 #sum = sum + temp;
        addi $t1, $t1, 1 #i++;
        bgt $t1, $t2, exit #(i>n)? goto exit; : goto loop;
        j loop

    exit:
        #Store sum at @result.
        la $t3, result
        sw $t0, 0($t3)

        #Show "The sum of the squares is: " message.
        la $a0, prompt2
        li $v0, 4
        syscall

        #Show @result integer (sum).
        lw $a0, 0($t3)
        li $v0, 1
        syscall

        #Exit.
        jr $ra

检查出来,问候。

答案 1 :(得分:-2)

#以下代码可能对你有帮助

.data

prompt: .asciiz "Enter the value of N (must be positive): "

.text

.globl main

main:

li $v0,4

la $a0, prompt

syscall

li $v0, 5

syscall

move $t1, $v0

add $t2,$t1,1

mul $t3,$t1,2

add $t4,$t3,1

mul $t5,$t4,$t2

mul $t6,$t5,$t1

div $t7,$t6,6



move $a0, $t7
     
li $v0, 1        #print value

syscall

li $v0, 10

syscall