2016-03-28 31 views
1

我正在嘗試寫入從用戶處取得的求和整數的MIPS代碼,直到用戶輸入字符「*」。從字符中加入整數循環退出

輸出會喜歡 「1 4 3 *總計:8」

我寫的代碼終止循環條件時用戶輸入 「-1」,而不是 「*」。我試着寫'*'語法而不是-1,但它沒有給出總和。用戶輸入「*」字符時如何退出循環?這是我的第一個問題,這裏是我的工作代碼「-1」。

# $s0=Sum, $s1=Checkvalue 

     .data     # Data memory area 
prompt: .asciiz "Total: " 
     .text     # Code area 

main: 
     move $s0, $zero  # Sum is made "0" 
     li  $s1, -1   # Checkvalue is made "-1" 

loop: bne $s0, $s0, exit # Infinite loop is described 
     li  $v0, 5   # Read integer into $v0 
     syscall     # Make the syscall read_int 

     move $t0, $v0   # Move the integer read into $t0 

     beq $t0, $s1, exit # If the read value is equal "-1", exit 
     add $s0, $t0, $s0  # Add the read integer to sum 
     j  loop    # Return loop 

exit: 
     li  $v0, 4   # Syscall to print string 
     la  $a0, prompt 
     syscall 

     move $a0, $s0   # Syscall to print string 
     li  $v0, 1 
     syscall 

     li  $v0, 10   # Syscall to exit 
     syscall 

# Reference: www.es.ele.tue.nl/~heco/courses/ProcDesign/SPIM.ppt 

我的第二個問題是我使用了「系統調用」,我的用法是否適用於stdin和stdout,系統函數?

非常感謝。

回答

2

您正在讀取整數,如-1,並且很明顯,*不是整數。要退出循環,您必須弄清楚如何讀取字符和整數。如果您的號碼只有一位數字,您可以將所有輸入作爲字符讀取,並根據需要轉換爲整數。否則,您將不得不讀取字符串並將其轉換爲整數。

至於你的第二個問題,你是正確的使用系統調用標準輸入和輸出系統功能。

+0

謝謝。我發佈了一個與此[這裏]有關的新問題(http://stackoverflow.com/questions/36296223/comparing-two-strings-in-mips) – bieaisar