运行代码时,出现最小值错误,如何修复?
.data
prompt: .asciiz "Enter your first and last name: "
max_msg: .asciiz "\nMaximum ASCII value: "
min_msg: .asciiz "\nMinimum ASCII value: "
newline: .asciiz "\n"
.text
.globl main
main:
# Prompt for input
li $v0, 4 # system call for print string
la $a0, prompt # load address of prompt
syscall
# Read input
li $v0, 8 # system call for read string
la $a0, buffer # load address of buffer
li $a1, 255 # set maximum length of input
syscall
# Find maximum and minimum ASCII values
la $t0, buffer # load address of buffer into $t0
li $t1, 0x20 # initialize $t1 to the ASCII value of space
li $t2, 0x7F # initialize $t2 to the largest possible ASCII value
li $t3, 0x00 # initialize $t3 to the smallest possible ASCII value
li $t4, 0 # initialize $t4 to 0
loop:
lb $t5, ($t0) # load byte from current position
beq $t5, 0, done # if byte is null terminator, we're done
# if byte is a space, skip it
beq $t5, $t1, next
# if this is the first non-space character, initialize $t4
beq $t4, 0, init
# find maximum ASCII value
bgt $t5, $t3, is_max
j is_min
is_max:
move $t3, $t5 # set $t3 to current byte
j next
# find minimum ASCII value
is_min:
blt $t5, $t2, set_min
j next
set_min:
move $t2, $t5 # set $t2 to current byte
j next
init:
# initialize $t4 to the first non-space character
move $t4, $t5
j next
next:
addi $t0, $t0, 1 # move to next byte
j loop # jump to loop
done:
# Print results
li $v0, 4 # system call for print string
la $a0, max_msg # load address of max message
syscall
li $v0, 1 # system call for print integer
move $a0, $t3 # load maximum ASCII value
syscall
li $v0, 4 # system call for print string
la $a0, min_msg # load address of min message
syscall
li $v0, 1 # system call for print integer
move $a0, $t2 # load minimum ASCII value
syscall
li $v0, 4 # system call for print string
la $a0, newline # load address of newline
syscall
# Exit program
li $v0, 10 # set system call number to 10 for exit
syscall # perform system call to exit
.data
buffer: .space 256 # allocate space for input buffer
这里我的名字的最大ascii值是正确的,但最小值是错误的。
我的输出:
输入您的名字和姓氏:Isaac Newton最大ASCII值:119最小ASCII值:10
我的预期输出:
输入您的名字和姓氏:Isaac Newton最大ASCII值:119最小ASCII值:73
我该怎么解决?
1条答案
按热度按时间xxslljrj1#
MIPS system call 8类似于C中的fgets(),它在输入的末尾包含一个 newline。您应该检查newline的ascii值,正如您可能已经猜到的那样,是10。
现在,为什么它会在换行符之后停止?好吧,缓冲区的其余部分用一个 * 单个 * 空字符填充。这就是为什么它总是 * 将minValue设置为10,然后立即终止程序。要解决这个问题,您需要做的就是执行一个检查,查找ascii值为10的字符(在您的情况下,您很可能只需要将
beq $t5, 0, done
更改为beq $t5, 10, done
)。我希望这有助于消除您可能遇到的任何困惑。编辑:* 正如Peter在下面提到的,这种实现可能会导致程序中的漏洞。有关原因的精彩解释,请参阅下面的评论。*