[英]printing a right triangle in mips
這是我寫的代碼來嘗試解決這個問題。 我的代碼要結束; 根本沒有循環,而且似乎只為輸入的任何數字打印兩顆星。
li $t1,1 #start row at 1
li $t2,1 #start col at 1
li $t3,0 #temp=0
outer:
bgt $t1,$t0,done #row < user input
addi $t1,$t1,1 #row++
inner:
bgt $t2,$t1,done #col<row
addi $t2,$t2,1 #col++
#print star
la $a0,Star
li $v0,4
syscall
addi $t3,$t3,1 #adds 1 to temp after every print
beq $t2,$t3,outer #if col = temp counter jump to outer
j inner #restart loop
#code to endl;
la $a0,endl
li $v0,4
syscall
j outer #restart loop
以下是預期輸出的示例:
Please enter the edge length of the base of right triangle: 5
*
**
***
****
*****
您不需要在單個循環中使用多個分支語句。 您的代碼只打印兩顆星的原因是您沒有將內部循環的計數器重置為 1。因此它循環兩次,然后退出循環。
這是我的代碼,它完全符合您的要求:
.data
prompt: .asciiz "Please enter the edge length of the base of right
triangle: "
newLine: .asciiz "\n"
star: .asciiz "*"
.text
main:
li $v0, 4 # print the prompt
la $a0, prompt
syscall
li $v0,5 #take user input
syscall
move $s0, $v0 # move the input to $s0
li $t0, 0 # load 0 at t0
outerLoop:
beq $t0, $s0, end #(for i=0;i<=baseLength;i++)
#if t0=s0 branch to end
addi $t0, $t0, 1 # increment i
li $t1, 1 #load 1 at t1
jal changeLine #jump to changeLine
innerLoop:
bgt $t1, $t0, outerLoop #(for j=0;j<=i;j++)
# if t1=t0 branch to outerLoop
li $v0, 4 # print star
la $a0, star
syscall
addi $t1, $t1, 1 # increment j
j innerLoop # jump to innerLoop
changeLine:
li $v0, 4 # new line
la $a0, newLine
syscall
jr $ra # jump to after the call instruction
end:
li $v0, 10 # end of program
syscall
.data prompt: .asciiz "請輸入直角三角形底邊的長度:" ExitMsg: .asciiz "退出程序。" star: .asciiz "*" newLine: .byte '\\n' .text ## 你的主線程序會詢問用戶直角三角形底邊的長度。 輸入:
li $v0, 4 la $a0, 提示系統調用
li $v0,5 #take in input
syscall
#This will take the edge length of the base of the right triangle as argument $a0.
move $a0, $v0 #move the input to a0
# If user enter 0 or a negative number, the program exits.
bgtz $a0, printTriangle #branch if greater than zero
li $v0, 4
la $a0, ExitMsg
syscall
li $v0,10 #end program
syscall
# Otherwise, the program will pass the edge length value in $a0 to the printTriangle procedure, which will print the triangle as described.
printTriangle: #Write a procedure called printTriangle.
li $t0, 1 #keep track vervicle
li $t1, 1 #keep track Horizontal
move $t3, $a0 #INPUT INT as t3
# It will then print the triangle with stars.
loop:
li $v0, 4
la $a0, star
syscall
beq $t0, $t1, exitLoop #if counter 0 = counter 1, exitLoop to new line
#print an *
addi $t0, $t0, 1 #otherwise incriment t0 location in array
j loop #looping up to beginning
exitLoop:
li $v0, 4 #print newline
la $a0, newLine
syscall
beq $t1, $t3, input #if t1 = INPUT INT as t3, The mainline code will then loop back to ask the user for a new edge length.
#else
li $t0, 1 #set t0 back to 0
addi $t1, $t1, 1 # incriment t1 location in array
j loop
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.