在程序集中查找数组的平均值(nasm)

时间:2017-10-23 04:00:06

标签: arrays assembly average

我有一个程序首先添加了阵列中的所有内容并打印出来,现在我试图获得阵列的平均值,但我遇到了麻烦。

    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                    ;

循环之后的部分是我试图划分它的地方。

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

我认为我越来越接近,数组总和为10,我的程序得到结果5,当它应该是2时,任何人都可以帮助摆脱一些亮点吗?

请,谢谢你:)

1 个答案:

答案 0 :(得分:0)

想出来

你需要使用fdivp来划分st1,st0