我只有几周的时间使用MARS学习技巧。我试图根据用户在控制台提示符下输入的int循环显示“我喜欢计算机科学”。因此,如果用户在提示符下输入4,则“我爱计算机科学”将在控制台上打印4次。我还添加了输出循环时间的总和。在我开始尝试根据用户输入的int使程序循环之前,总和可以完美地打印到控制台。我已经把这个弄糟了几个小时,确实陷入了困境。我知道这个程序可能充满了菜鸟错误,但到目前为止,这是我到目前为止所掌握的。
.data
userPrompt : .asciiz "Enter a number: "
love: .asciiz "I love computer science! "
sumMessage: .asciiz "The sum of integers from 1 to N is: "
list: .word 0
.text
addi $t3,$zero,1 # $t3 = int count = 1;
addi $t1,0 # $t3 = int sum = 0
li $v0,4 # system call code for print_str
la $a0,userPrompt # address of string to print
syscall # print the string
li $v0,5 # read_int syscall
syscall
while:
move $t0,$v0
ble $t0,$t3,exit #while input <= limit
addi $t1,$t1,1 #increment counter
syscall #call
j while #jumps back to the top of loop
cs:
li $v0,4 # syscall code to print a string
la $a0,love
syscall # print a space
j while
stored:
addi $t7,1 # t7 has the number to be stored.
la $s1,list # $s1 = address
initlp:
bgt $t7,$t0,initDone # exit loop after storing user input integers. t0 has that value.
sw $t7,($s1) # list[i] = $t7
addi $s1,$s1,4 # step to next array cell
addi $t7,$t7,1 # increment the register $t7 to next number
b initlp
initDone:
la $s1,list # load base addr
addi $t7,1 # t7 = counter
move $t2,$zero # t2 will store the sum.
loop:
bgt $t7,printSum # add the numbers
lw $t4,0($s1) # load
addi $s1,4 # increment pointer
add $t2,$t2,$t4 # update sum
addi $t7,1 # increment the loop counter
b loop
printSum: # print sum message
li $v0,4
la $a0,sumMessage
syscall
# print value of sum
li $v0,1
addi $a0,0
syscall
exit:
# exit
li $v0,10
syscall
输入要循环的数字后,程序结束。在我尝试循环“我爱计算机科学”之前,Sum一直在工作。
Expected output:
Enter a number: 5
I love computer science!
I love computer science!
I love computer science!
I love computer science!
I love computer science!
The sum of integers from 1 to N is: 15