如何用RISC-V汇编语言打印总计?

时间:2020-11-08 05:03:00

标签: assembly riscv

该代码应该将数字存储在数组中,然后打印正数的总数和负数的总数。我不确定自己在做什么错! 它打印出没有总数的消息。我在RARS模拟器中使用RISC-V汇编语言

这是我目前的结果:

Positive Integers Total: 
Negative Integers Total: 
Negative Integers Total: 
-- program is finished running (0) --

不显示总计值。我该如何解决?

#----Calculate the Sum of Positive and Negative Numbers In An Array----#
########################################################################
    .data
array:      .word 22,-35,48,10,-15,-30,25,20,-1,-26,-18,1,2,3,4,5,6,7,-9,1,-4,-3,-2,1,6,0 #array input
positiveSum:    .word 0
negativeSum:    .word 0

#outcome messages
position:       .word 0 #index posisiont of array
length:     .word 9
posTotal:       .ascii "\nPositive Integers Total: "
negTotal:       .ascii "\nNegative Integers Total: "

    .text
main:
       
       la t0,array      #load array to register t0 
       lw t1,position
       lw s1, positiveSum   #load the positive sum to s1, and negative sum to s2
       lw s2,negativeSum

loop:
           #calculate the index position in terms of memory
           #each integer needs 4 bytes
           #so shift left the value in t1 and store it in t3
    slli t3,t1,2
        add t3,t3,t0        #add the base address and the above result
        lw t4,0(t3)     #load the word from above address into t4
        beqz t4,exit        #exit loop when reaching 0
        j checkSign     #if value is not 0 jump to check integer sign

checkSign:
               
        bltz t4,addNegative     #check if array value is negative 
    j addPositive       # if yes goto addnegative
                        #if not goto addpositive
               
addPositive:
        add s1,s1,t4        #add all positive integers to s1 register
        j increment     #increment
               
addNegative:
        add s2,s2,t4        #add the negative integers to the s2 register
        j increment     #increment
           
increment:
        addi t1,t1,1        #increment the current index in t1 by 1
        j loop
          
exit:               #end of program
        la a0,posTotal   
        li a7,4         #print the positive sum 
        ecall
        
        la a0,negTotal
        li a7,4     #print the negative sum 
        ecall

    ori a7, zero, 10    #program exit system call
    ecall           # exit program

1 个答案:

答案 0 :(得分:0)

您仅打印posTotal和negTotal。将它们转换为ascii格式后,还需要打印positiveSum和negativeSum。

我不知道您的ecall的工作原理,但是当您将Sums中的ascii放入a0时(如果此解决方案始终有效),或者如果ecall可以花费多个调用,您需要添加两个调用来调用ecall参数使用a1将Sum作为第二个参数。

您两次打印Negative Integers Total:是因为您没有在字符串末尾添加\0,所以第一次打印第一个字符串,但继续打印直到找到\ 0。

我建议您在字符串之间添加对齐指令,例如.balign 4

posTotal:       .ascii "\nPositive Integers Total: \0"
.balign 4
negTotal:       .ascii "\nNegative Integers Total: \0"

j checkSign和第二个j increment没用。

相关问题