下面我分享了一个示例MIPS汇编程序,它从控制台读取一系列整数。有效条目介于-110和120(含)之间。如果条目无效,则拒绝该条目并在屏幕上显示错误消息。 (供参考,以了解您的代码的逻辑)。从这段代码开始,我还想补充一点,当数字计数变为8时,程序将停止阅读。你有任何想法吗?
# Program Description
# Reads integers from the keyboard and displays the total
# number of entries, sum, and integer average
# Reads until -1 is entered
# Only accepts values between 10 and 99 (inclusive)
#
# t0 = 0 # Total
# t1 = 0 # Count
# t2 = -110 # Min
# t3 = 120 # Max
# t4 = -467 # Stop
#
###########################################################
# Register Usage
# $t0 Running total
# $t1 Entry count
# $t2 Minimum value
# $t3 Maximum value
# $t4 Stop value
# $t5 Entry (from user)
###########################################################
.data
enter_p: .asciiz "Enter a value between -110 and 120 (inclusive): "
invalid_p: .asciiz "Invalid value\n\n"
count_p: .asciiz "\n\nNumber of entries: "
total_p: .asciiz "\nTotal: "
average_p: .asciiz "\nInteger average: "
noentry_p: .asciiz "\n\nNo valid values entered\n"
###########################################################
.text
main:
# Initialize values
li $t0, 0 # Total
li $t1, 0 # Count
li $t2, -110 # Min value
li $t3, 120 # Max value
li $t4, -467 # Stop value
readLoop:
# Get value
li $v0, 4
la $a0, enter_p
syscall # Prompt for value
li $v0, 5
syscall # Read entry
# Validate value
beq $v0, $t4, getResults
blt $v0, $t2, entryInvalid
bgt $v0, $t3, entryInvalid
# If program gets here, the entry is valid
add $t0, $t0, $v0 # Add entry to total
addiu $t1, $t1, 1 # Increment counter
b readLoop # Loop
entryInvalid:
li $v0, 4
la $a0, invalid_p
syscall # Print error message
b readLoop # Go back and read more
getResults:
beqz $t1, zeroEntries # Prevent divide by 0
# Display number of entries
li $v0, 4
la $a0, count_p
syscall # Print 'count' string
li $v0, 1
move $a0, $t1
syscall # Print count
# Display total
li $v0, 4
la $a0, total_p
syscall # Print 'total' string
li $v0, 1
move $a0, $t0
syscall # Print total
# Calculate and display average
li $v0, 4
la $a0, average_p
syscall # Print 'average' string
li $v0, 1
div $a0, $t0, $t1 # Put results directly into $a0
syscall # Print average
b mainEnd # Done
zeroEntries:
li $v0, 4
la $a0, noentry_p
syscall # Print 'no entries' message
mainEnd:
li $v0, 10 # End Program
syscall