简体   繁体   English

嵌套循环产生错误Assembly / x86 / MASM

[英]Nested loop giving errors assembly/x86/MASM

I made a nested loop to try to find the composite numbers from 1...400 and save them to an array. 我做了一个嵌套循环,尝试从1 ... 400中查找复合数字并将其保存到数组中。 Its not working out so great, unfortunately. 不幸的是,它的效果不是很好。 Can anybody help me out? 有人可以帮我吗?

UPPER_LIMIT equ 400
    .data
    CoArray DWORD 500 DUP(?)

Push the offset of array in main before making the function call: 在进行函数调用之前,将array的偏移量推入main

main PROC
   push OFFSET CoArray
   call calc
main ENDP

And this is the procedure itself: 这是过程本身:

calc PROC
    push    ebp                     ; Save base pointer
    mov     ebp, esp                ; Base of stack frame
    mov     esi,[ebp + 8]           ; offset of the array

    ; esi now holds offset of the array

    mov     ecx, 4
L1:
    cmp     ecx, UPPER_LIMIT
    jnle    done

    mov     ebx, 2
L2: 
    mov     edx, ecx
    sub     edx, 1
    cmp     ebx, edx
    jge     loopOne
    mov     eax, ecx
    cdq
    div     ebx
    cmp     edx, 0
    je      composite
resume:
    inc     ebx
    jmp     L2
loopOne:
    inc     ecx
    jmp     L1

done:
    pop     ebp
    ret     4

composite:
    mov     [esi], ecx                                      ; Add the number to the array and increment esi
    add     esi, TYPE DWORD
    jmp     resume
calc ENDP

I should mention that it asks for the user to enter a integer in a range (1 to 400) and stores it in a variable. 我应该提到,它要求用户输入一个介于1到400之间的整数并将其存储在变量中。 However, when I enter 10 the program terminates immediately. 但是,当我输入10时,程序将立即终止。 However, if I enter 20 or higher it hangs up. 但是,如果我输入20或更高,它将挂断。 Very odd. 很奇怪。

There's one big problem with your code, but it's not dependent on any sort of user input so it's not causing the problem you described at the end of your question. 您的代码有一个大问题,但是它不依赖于任何类型的用户输入,因此不会引起您在问题末尾描述的问题。 I'm going to assume that paragraph is irrelevant and describes a different version of your code that you haven't posted. 我将假设该段无关紧要,并描述了您尚未发布的代码的其他版本。

The problem is that once your code finds a composite number it's not moving on to next possible composite number. 问题在于,一旦您的代码找到了一个复合数字,它就不会继续前进到下一个可能的复合数字。 After placing the composite number in the array your code continues to look for more divisors of the number it's already determined to be composite. 将组合数字放入数组后,您的代码将继续寻找已确定为组合数字的除数。 This means composite numbers will get placed in the array multiple times, once for each divisor other than 1 and itself. 这意味着合成数将多次放置在数组中,每个除数(除1本身)以外的除数一次。 To solve this problem simply have the jmp resume statement at the end of your procedure jump to loopOne instead. 要解决此问题,只需将过程末尾的jmp resume语句跳转到loopOne

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM