简体   繁体   English

查找装配体中数组的平均值(nasm)

[英]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? 我想我越来越接近了,数组的总和为10,我的程序得到的结果为5,当它应该为2时,有人可以帮忙弄清楚吗?

please and thank you :) 谢谢,麻烦您了 :)

Figured it out 弄清楚了

you need to use fdivp that divides st1, by st0 您需要使用fdivp将st1除以st0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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