Floating point exceptions in x86 NASM assembly using div instruction

I have an assignment where I must take input of a number, and figure out all prime numbers up to but not exceeding that number. For example if I entered 9 into the program, it should print 3, 5, and 7.

My plan to determine if a number is prime or not is to divide it by 2 and check if the remainder is 0. If the remainder is 0 the program subtracts 1 from the dividend, and loops back to the top to divide again. If the remainder != 0 it prints it to the screen, and decrements the dividend again. This happens until the dividend is 0. Only this isn't what is happening, for whatever reason whenever I use the DIV instruction I always get floating point exceptions and I can't seem to figure out why or how to solve it. Anyone have any ideas on how I can fix this?

    Code: %INCLUDE      "csci224.inc"

    SEGMENT .data
    prompt:     DD      "Please enter a number: ",0     ; prompt string 
    message:    DD      " is prime.", 0                 ; displays when n is prime
    invalid:    DD      "Invalid entry.", 0
    i:          DD      2                               

    SEGMENT .bss
    input:      RESD    100         ; not really necessary, ignore this

    SEGMENT .text
    main:

    mov     edx, prompt
    call    WriteString

    call    ReadInt

    mov     esi, eax                ; move eax into esi to use as index for loop

    myloop:

    xor     edx, edx                ; clear registers
    xor     ecx, ecx
    xor     eax, eax

    mov     eax, dword 2            ; mov 2 to eax
    div     ecx                     ; ecx/eax | n/2

    dec     esi                     ; decrement loop counter
    dec     ecx                     ; decrement numerator

    cmp     edx, dword 0            ; is remainder zero?
    je      myloop                  ; YES - not prime - jump back to top

    mov     eax, edx                ; NO  - move to eax and print
    call    WriteInt
    call    Crlf

    cmp     esi, 0                  ; is counter zero?
    jz      finished                ; YES - end loop

    jmp     myloop                  ; NO  - loop again

finished:
    ret

在这部分代码中:

xor     ecx, ecx                ; Clears ecx (set to 0)
xor     eax, eax                ; Clears eax (set to 0)

mov     eax, dword 2            ; Sets eax to 2
                                ; NOTE: you had just set it to 0 in the prior step)

; PROBLEM; the following code computes eax/ecx, which is 2/0 - the comment is wrong

div     ecx                     ; ecx/eax | n/2
链接地址: http://www.djcxy.com/p/15898.html

上一篇: execv示例是segfaulting

下一篇: 使用div指令的x86 NASM程序集中的浮点异常