这是我的解决方案,我想知道它是否正确以及解决它的另一种方法
include 'emu8086.inc'
org 100h
mov CX,n
lea SI,a
mov AL,0
start_sum_a: ;sum all the n elements of the first array
add AL, [SI]
inc SI
loop start_sum_a
mov CX,n
lea SI,b
start_sum_b: ;sum all the n elements of the 2nd array to
add AL, [SI] ;the first sum
inc SI
loop start_sum_b
call print_num ;print the sum
ret
a db 1,3,5,7,9,11,13,15,17,18
b db 0,2,4,6,8,10,12,14,16,19
n dw 10
DEFINE_PRINT_NUM
DEFINE_PRINT_NUM_UNS
最佳答案
i'd like to know if it's correct
您的解决方案看起来不错,尽管我有预感“emu8086.inc”中定义的函数print_num更希望得到AX
寄存器中的数字。因此,最好将 mov AL,0
指令更改为 xor ax,ax
,这将清除整个 AX
寄存器,而不仅仅是其低字节 >AL
.
what is another way of solving it
如果为两个数组设置单独的指针,则可以选择在单个循环中完成工作。
lea si, a
lea di, b
mov cx, n
xor ax, ax
start_sum:
add al, [si] ;Element of a array
add al, [di] ;Element of b array
inc si
inc di
loop start_sum
但是由于这些数组的起始点在内存中相距一定距离 (10),因此有一个仅使用 1 个指针的解决方案:
lea si, a
mov cx, n
xor ax, ax
start_sum:
add al, [si] ;Element of a array
add al, [si + 10] ;Element of b array
inc si
loop start_sum
最后,由于这些数组在内存中相邻,因此循环可以更简单。只需将迭代次数加倍即可(Peter Cordes 的建议之一):
lea si, a
mov cx, n
shl cx, 1 ;Double the counter
xor ax, ax
start_sum:
add al, [si] ;Element of a array or b array
inc si
loop start_sum
关于assembly - 两个数组的总和,每个数组 n 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45900051/