小编Bar*_*jak的帖子

通过C语言中的整数转换进行浮点数比较

我想得到一个确切/准确的答案,为什么下面的代码打印出不同的结果:

#include "stdio.h"
int main(void)
{
    int a = 9;
    int b = 10;
    printf("%d\n", (double)a / (double)b == 0.9); /* prints 0 */
    printf("%d\n", (double)9 / (double)10 == 0.9); /* prints 1 */
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我认为这可能是编译器依赖的,我的是gcc(GCC mingw Windows7)4.8.1和gcc(Debian 4.7.2-5)4.7.2.

非常感谢你!

UPDATE!

我使用和不使用-std = c99选项生成汇编代码,这应该有助于理解这里发生的事情.

没有-std = c99(这给出了结果0/1):

    .file    "a.c"
    .section .rodata.str1.1,"aMS",@progbits,1
.LC0:
    .string  "%d\n"
    .section .text.startup,"ax",@progbits
    .p2align 4,,15
    .globl   main
    .type    main, @function
main:
.LFB11:
    .cfi_startproc
    pushl %ebp
    .cfi_def_cfa_offset 8
    .cfi_offset 5, -8
    movl %esp, %ebp
    .cfi_def_cfa_register 5 …
Run Code Online (Sandbox Code Playgroud)

c floating-point comparison gcc

5
推荐指数
1
解决办法
306
查看次数

标签 统计

c ×1

comparison ×1

floating-point ×1

gcc ×1