![](/img/trans.png)
[英]How to print the total of positive and negative numbers in RISC-V Assembly
[英]How to print the total in RISC-V Assembly language?
此代码应该将数字存储在数组中,然后打印正数的总数和负数的总数。 我不确定我做错了什么! 它打印出没有总数的消息。 我在 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
您只打印 postTotal 和 negTotal。 将它们转换为 ascii 格式后,您还需要打印 positiveSum 和 negativeSum。
我不知道您的 ecall 是如何工作的,但是当您将 Sums 的 ascii 放入 a0 时,您需要添加两个对 ecall 的调用(此解决方案将始终有效),或者如果 ecall 可以采用多个参数放置使用 a1 作为第二个参数求和。
您得到了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
没用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.