我正在自学组装。我想求偶数之和。但是,它不起作用,我不明白为什么,它没有显示任何错误。
我的代码如下
mov ebx, 0;
mov ESI, [arr];
mov ECX, [arr_size];
sumeven:
push ebx;
mov eax, dword ptr[ESI];
mov ebx, 2;
cdq
idiv ebx;
cmp edx, 0;
je adding;
adding:
pop ebx;
add ebx, dword ptr[ESI];
add ESI, 4;
loop sumeven;
mov result, ebx;
我在c语言中使用内联汇编。
在代码中,当数字为偶数时,您会跳转到标签 adding:,但当数字为奇数时,您会跳到同一个标签中,因此您总是进行求和。 正确的代码是:
mov ebx, 0;
mov esi, [arr];
mov ecx, [arr_size];
jecxz emptyarr
sumeven:
push ebx;
mov eax, [ESI];
mov ebx, 2;
cdq
idiv ebx;
cmp edx, 0;
pop ebx;
jne notadding;
add ebx, dword ptr[ESI];
notadding:
add esi, 4;
loop sumeven;
emptyarr:
另一种解决方案可能是:
cld ; clear string direction flag for "lods"
xor ebx, ebx; ; fast clear ebx register: the even sum
mov esi, [arr]; ; load pointer to array into esi reg.
mov ecx, [arr_size]; ; load size of the array into ecx reg.
jecxz EmptyArr ; if empty array, terminate the routine
SumEven:
lodsd ; mov eax,[esi], esi=esi+4
test eax, 1; ; if less significant bit is 1, odd element
jne NotAdding ; if odd element skip the sum
add ebx, eax; ; add the element to the sum reg.
NotAdding:
dec ecx ; ecx= ecx-1
jnz SumEven ; if ecx<>0 go to SumEven
EmptyArr:
注意:如果您使用 32 位寄存器(如 EAX 寄存器)将数据移入或移出内存,例如:
mov eax, dword ptr [esi]
或 mov dword ptr [esi], eax
,
您不需要使用类型转换“dword ptr”指定数据的大小。
您可以简单地写:mov eax, [esi]
或mov [esi], eax
。
我添加了不等于0的条件,并且它起作用了。
cmp edx, 0;
je adding;
jne notequal;
notequal:
---
0到30的偶数之和
.model small
.stack 100h
.data
arrtxt db "the sum of even number 0 to 30 is : ",10,'$'
arr dw 8 dup('$')
num dw ?
.code
main proc
mov ax,@data
mov ds,ax
mov si,offset arr
mov cx,0
mov dx,offset arrtxt
mov ah,9
int 21h
mov bx,2
l1:
cmp cx,30
jg print
mov ax,cx
mov dx,0
div bx
cmp dx,0
jz addition
inc cx
jmp l1
addition:
add num,cx
inc cx
jmp l1
print:
mov cx,0
arrr:
MOV AX,0
mov ax,num
mov bx,10
cmp ax,0
je getarr
mov dx,0
div bx
add dx,48
push dx
mov num,ax
inc cx
jmp arrr
getarr:
pop dx
mov ah,2
int 21h
loop getarr
mov ah,4ch
int 21h
main endp
end main