使用div指令在x86 NASM程序集中浮点异常

时间:2013-10-17 02:55:57

标签: assembly x86 nasm floating-point-exceptions

我有一项任务,我必须输入一个数字,并找出所有素数,但不超过该数字。例如,如果我在程序中输入9,它应该打印3,5和7。

我确定数字是否为素数的计划是将其除以2并检查余数是否为0.如果余数为0,则程序从被除数中减去1,然后循环返回到顶部再次除以。如果余数!= 0则将其打印到屏幕上,并再次递减红利。这种情况一直发生,直到被除数为0.只有这不是正在发生的事情,无论出于什么原因,每当我使用DIV指令时,我总是得到浮点异常,我似乎无法弄清楚为什么或如何解决它。任何人对我如何解决这个问题都有任何想法?

    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

1 个答案:

答案 0 :(得分:7)

在代码的这一部分:

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