首页 > 解决方案 > 在程序集中使用 printf 正确显示浮点数

问题描述

该程序旨在添加 2 个浮点数并显示它们各自的结果,但程序给出了不需要的结果,我不明白为什么需要为浮点数分配 16 个字节而不是双精度数占用 8 个字节,那么为什么不只为浮点数分配 8 个字节呢?

    .text
    .globl  main
    .type   main, @function
main:
    subl    $12,    %esp    # allocate enough memory for a floating point value
    flds    (V0)        # load loading single precision variable 1
    flds    (V1)        # load single precision variable 2
    fadd    %st(1), %st(0)      # add both of them [ NOTE: reg ST(0) contains correct result ]
    fstpl   (%esp)      # store the float
    pushl   $.LC0
    call    printf
    addl    $16,    %esp    # return allocated mem to OS [ 12 + 4 = 16 ]
    ret

.LC0:   .string "%f\n"

V0: .float 9.3
V1: .float 9.4

标签: assemblyx86floating-point32-bitgnu-assembler

解决方案


对我来说看起来有问题;ESP在调用之前是 16 字节对齐的main(它会推送一个 4 字节的返回地址),因此它应该sub $12, %esp在打电话给printf.

如果您使用 C 编译器编译 C 函数,您会看到这样的结果。

我还建议使用flds单精度加载​​和fstpl双精度存储,以明确大小。这也是错误的;加载和存储默认是一样的,这个程序需要浮动加载和双重存储。(默认为单精度float、双字)

printf "%f"需要 adouble因为无法将floatC 中的 a 传递给可变参数函数:默认促销适用。)


推荐阅读