2013-10-17 68 views
0

我有一個任務,我必須輸入一個數字,並計算出所有素數達到但不超過該數字。例如,如果我在程序中輸入了9,它應該打印3,5和7.x86 NASM彙編中使用div指令的浮點異常

我計劃確定一個數是否爲素數是將它除以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 

回答

5

在代碼中的這一部分:

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