【发布时间】:2020-06-09 18:35:45
【问题描述】:
我正在编写 MIPS 汇编代码来计算字符串中的位数。例如,如果用户字符串是:“qapww9...$$$64” 输出为 3。
我使用 ascii 代码来设置整数的边界(48 代表 0,57 代表 9)。我想检查每个字符是否大于或等于 0,然后小于或等于 9,如果是,则将一个添加到计数器,然后移动到下一个字符。输入字符串后我的代码失败了
编辑
: 我收到反馈说我没有正确递增字符串的每个字符。我目前在做的是addi $t0, $t0, 1。
# MIPS assembly language program to count the number of decimal digits in an ascii string of characters.
# $a0 = $t0 = user input
# $t1 = counter
# $t2 = temporary register to hold each byte value
.data
length: .space 100
p: .asciiz "\nEnter a string: "
p2: .asciiz "\nNumber of integers: "
.text
#Prompt User for String
la $a0, p #print prompt
li $v0, 4 #load string stored in v0
syscall #display prompt string
#Get user input
li $v0, 8 #load string stored in v0
la $a0, length #set string length to 100
addi $a1, $0, 100 #add length 100 to regist $a1
syscall
move $t0, $a0 #user input is now in register $t0
addi $t1, $0, 0 #initialize counter
#loop to check if greater or equal to 0
lowerBound:
lb $t2, 0($t0) #load first character of user input into $t2
bge $t2, 48, upperBound #branch to upperBound checker if char is greater than or equal 0
addi $t0, $t0, 1 #increment to next character in string
beqz $t0, end #if character = 0 (end of string), end
j lowerBound
#loop to check if less than or equal to 9
upperBound:
ble $t2, 57, count_digits #if in the range 0-9, just to count digits and add 1 to counter
j lowerBound #loop through again
count_digits:
addi $t1, $t1, 1 #add 1 to counter
j lowerBound
end:
li $v0, 4 #load string print service
la $a0, p2 #load address of prompt 2 inro $a0
syscall #print prompt
la $a0, ($t1) #load address of count into $a0
li $v0, 1 #specify print integer service
syscall #print count
【问题讨论】:
-
您一遍又一遍地加载同一个字符。您的柜台不是
$t2,您打算如何到达end? -
@Jester 怎么样?我在哪里出错,我没有增加字符串中的每个字符来检查。我打算使用以下行结束:beqz $t2, end ... 我相信这意味着如果 $t2 的字符 = 0,那么这意味着字符串是空的,因此我完成了检查。
-
lb $t2, 0($t0)正在从$t0加载,$t0永远不会改变。此外,如果字符小于 48,您只需在lowerBound块中循环,您永远不会退出。 -
addi $t2, $t2, 1这不是移动到下一个字符吗?然后它再次循环通过lowerBound来检查下一个? -
$t2是您加载的字符。增加它是没有意义的。您想增加$t0,以便您可以使用它将下一个字符加载到$t2。
标签: assembly mips mips32 mars-simulator