简体   繁体   中英

Finding the average of an array in assembly (nasm)

I have a program that first added everything in the array and printed, now i'm trying to get the average of the array, but i'm having trouble with it.

    extern printf                   ; the C function to be called

    SECTION .data                   ; Data section

table           dd               1.0
                dd               1.0
                dd               3.5
                dd               2.0
                dd               1.5
N               equ             ($-table)/4     ; number of items in table


msg     db      "Average = %e",0x0a,0x00
temp    dq      0
;count  dd      0
sum     dd      0       

    SECTION .text                   ; Code section.

    global  main                    ; "C" main program 
main:                                   ; label, start of main program
    mov     ecx, N
    mov     ebx, 0
    mov     [count], ecx

        fldz                            ; st0 <- 0
for:    fld     dword [table + ebx*4]   ; st0 <- new value, st1 <- sum of previous
        fadd                            ; st0 <- sum of new plus previous sum   
        inc     ebx
        loop    for

    ;fldz
    fild    dword [count]           ; store count into fpu
    fdiv    st1, st0                ; divide sum by count (N) 

;;; get sum back from FPU
    fstp    dword [sum]             ; put final sum in variable

;;; print resulting sum
    fld     dword [sum]             ; transform z in 64-bit word
    fstp    qword [temp]            ; store in 64-bit temp and pop stack top


    push    dword [temp+4]          ; push temp as 2 32-bit words
    push    dword [temp]
    push    dword msg               ; address of format string
    call    printf                  ; Call C function
    add     esp, 12                 ; pop stack 3*4 bytes

    mov     eax, 1                  ; exit code, 0=normal
    mov     ebx, 0
    int     0x80                    ;

The section just after the loop is where i'm trying to divide it.

    fild    dword [count]           ; store count into fpu
    fdiv    st1, st0                ; divide sum by count (N) 

I think i'm getting close, with an array sum of 10, my program gets a result 5, when it should be 2, can anyone help shed some light?

please and thank you :)

Figured it out

you need to use fdivp that divides st1, by st0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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