2013-04-30 67 views
0

我想顯示循環索引的當前值MIPS的階乘,但是,我的循環根本不起作用。每次運行代碼時它都會凍結。假設我有一個for循環(i = 1; i < = 5; i ++),對於i的每個值,我想顯示當前階乘(i)。數字5實際上由用戶提供,換句話說,數字可以改變(1-10)。我試圖弄清楚爲什麼我的循環導致代碼凍結,但到目前爲止我沒有任何線索。您的幫助將非常感激。代碼是波紋管。不起作用。 MIPS

.data    # data declaration section; specifies values to be stored 
         # in memory and labels whereby the values are accessed 
Prompt: .asciiz "\nEnter the number to compute the factorial:\n" 
message: .asciiz "\nResult of computation is:\n" 

result: .word 0 


#-------------------------------- 
#  main function   | 
#-------------------------------- 

    .text    # Start of code section 
    .globl  main 
    main:    # Execution begins at label "main". The prompt is displayed. 


    li $v0, 4   # system call code for printing string = 4 
    la $a0, Prompt  # load address of string to be printed into $a0 
    syscall    # call operating system to perform operation; 
       # $v0 specifies the system function called; 
       # syscall takes $v0 (and opt arguments) 


# Read integer N    
    li $v0, 5 
    syscall 


    move $t0, $v0  #copy integer N into $t0 

    li $t1, 1  #initialize i=1 


loop: 
    blt $t0, $t1, exit_loop  # if number<1, exit... 
move $a0, $t0    # copy N into $ao 
jal fact    #else call fact 

sw $v0, result 


li $v0, 4   #Display message 
la $a0, message 
syscall 


li $v0, 1   #print result 
lw $a0, result 
syscall 

sub $t0, $t0, 1  #Decrement N by one, N-- 
j loop 



exit_loop: 
jr $ra #return address 



exit: #exit the program 
li $v0, 10 
syscall 


.globl fact 
.ent fact 
fact: 
    subu $sp, $sp, 8 
sw $ra, ($sp) 
sw $s0, 4($sp) 

li $v0, 1   #check base case 
beq $a0, 0, end_fact 

move $s0, $a0  #fact(n-1) 
sub $a0, $a0, 1 
jal fact 

mul $v0, $s0, $v0 #n*fact(n-1) 

end_fact: 

lw $ra ($sp) 
lw $s0, 4($sp) 
addu $sp,$sp, 8 
jr $ra 

#end of factorial function 

回答

1

您的問題是在指令在exit_loop標籤:

exit_loop: 
    jr $ra #return address 

你又跳進循環,因爲你沒有在你的主函數的開始保存$ra,你也沒有在發佈之前恢復它jr

事實上,您的代碼應該只是終止(syscall 10)而不是發出跳轉,因爲您正在實現主函數而不是函數從別處調用。

所以,我會改變該代碼:

exit_loop: 
    li $v0, 10 
    syscall 

尋找更多的到你的代碼,你已經擁有了代碼(標籤exit),因此你可能只是刪除您exit_loop代碼和分支到exit而不是exit_loop,該分支剛好在loop標籤後面。

+0

謝謝!它現在按預期工作。 – T4000 2013-04-30 16:08:58