MIPS汇编字符串总和

问题描述 投票:0回答:1

如何在MIPS Assembly中将具有随机数的字符串的值求和?

我尝试了很多事情但对我不起作用。

有人可以帮我吗?

.data
    correct_number:     .asciiz     "1234 5678 9012 3456"

.text
    la $t0, correct_number
    add $t1, $t1, $zero     #Iterator = 0
    add $t2, $t2, $zero     #Sum = 0
    addi $t3, $t3, 15       #Size = 15

    while:
        bgt $t1, $t3, endwhile

        sll $t9, $t1, 2     #4*i

        addu $t9, $t9, $t0  #correct_number[i)

        lw $t6, 0($t9)      #load the first byte

        addu $s7, $s7, $t6

        addi $t1, $t1, 1    #iterator + 1

        j while
    endwhile:

    li $v0, 1       #Print the sum
    la $a0, ($s7)
    syscall 

错误结果:-738593543

assembly mips
1个回答
0
投票

我假设您想查找correct_number中所有数字的总和,但不包括空格。对于"1234 5678 9012 3456",预期结果为66

尝试使用MIPS代码之前,先拥有高级伪代码总是有帮助的。在这种情况下,这是几行-

sum = 0
$t0 = address of correct_number
while *correct_number is not 0:   // this way, you can avoid '#Size = 15' in your solution
  ch = *correct_number
  if ch is not space:
    ch -= 48                      // convert the ASCII of digit to numeric value
    sum += ch
  correct_number++                // increment string pointer

// now sum contains the sum of all digits.

还有待翻译成MIPS-

.data
correct_number:     .asciiz     "1234 5678 9012 3456"

.text
la   $t0, correct_number    # $t0 = address of correct_number
move $t2, $zero             # $t2 = Sum = 0

while:
lb   $t1, ($t0)             # $t1 = load the current byte
beqz $t1, endwhile          # did we reach end of string?
beq  $t1, ' ', continue     # if not, is current char space?
subi $t1, $t1, '0'          # if not, convert the digit char to its numeric value
add  $t2, $t2, $t1          # sum += numeric_value

continue:
addi $t0, $t0, 1            # correct_number++ (increment pointer)
j while                     # and loop

endwhile:
li   $v0, 1                 # $v0 = 1 to print integer in $a0
move $a0, $t2               # move Sum to $a0
syscall                     # and print it


li $v0, 10                  # exit program
syscall 
© www.soinside.com 2019 - 2024. All rights reserved.