需要循环帮助以迭代方式将汇编中的sum变量相加

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

我正在尝试将以下C ++代码转换为Assembly(MASM,Irvine32):

const int SIZE = 10;

int numbers[SIZE] = {10,60,20,33,72,89,45,65,72,18};
int limit = 50;
int index = 0;
int sum = 0;

while( index < SIZE )
{
    if( numbers[index] <= limit )
    {
        sum = sum + numbers[index];         // sum += array[index];
    }
    index++;
}

[如果有人能弄清我要去哪里,我会在L1处出错:它只是喷出“ +10”。我相信这是因为我无法将sum = sum + numbers [index]转换为Assembly。如果有人可以帮助我做到这一点,那就太好了。我尝试翻译它(从“ total:mov esi,偏移量数字”到“ inc index”的行)显然是错误的。

.data
SYZ = 10
numbers DWORD 10, 60, 20, 33, 72, 89, 45, 65, 72, 18
limit DWORD 50
index DWORD 0
sum DWORD 0

.code
main PROC
mov eax, index
mov ebx, SYZ
top: cmp eax, ebx
jae next
jb total

total: mov esi, OFFSET numbers
mov ecx, limit

cmp [esi], ecx

jbe L1

L1: add eax, ebx

inc index

jmp top

next: mov edx, sum

call WriteInt



exit
main ENDP
END main
c++ assembly masm irvine32
1个回答
2
投票

您实现if的条件分支是错误的。它应该看起来像:

top:
...
    cmp [esi], ecx
    ja L1               ; conditional jump *over* an ADD instruction
    add eax, [esi]      ; [esi] is array[index] if you increment ESI properly...
L1: inc index
    jmp top

在您的C ++中,您可以看到,如果numbers[index] <= limit则要更新总和,否则只需增加索引并返回到“顶部”; aka重新检查停止条件。

您的原始汇编代码正在执行条件检查,然后不管结果如何继续进行。

    cmp [esi], ecx
    jbe L1               ; jump or fall-through to L1, condition irrelevant
L1: add eax, ebx

原始asm的C ++等效项是:

if( numbers[index] <= limit )
{
}

    sum += ebx;
    index++;

我不确定这是否可以解决您的所有问题,但肯定会解决其中一个问题。

© www.soinside.com 2019 - 2024. All rights reserved.