2 + 2 = 2 in C(双算术)

时间:2011-10-15 09:09:37

标签: c double sum

我完全不知道为什么它会为2a=2返回b=2 ..

有什么想法吗?

#include <stdlib.h>

int main()
{
    double a,b,c;
    printf("a=");
    scanf("%d", &a);
    printf("b=");
    scanf("%d", &b);
    printf("c=");
    scanf("%d", &c);

    printf("x=%d", a+b);

    return 0;
}

4 个答案:

答案 0 :(得分:2)

说明符"%d"需要一个整数,并且您传递的是double的地址。在scanf中使用错误的说明符会导致未定义的行为。

另外,在printf中使用错误的说明符是一回事。因为printf采用可变数量的参数a + b,所以双精度不能转换为整数。

答案 1 :(得分:2)

%d用于读取整数,使用%f%lf用于浮点数/双精度。

答案 2 :(得分:1)

printf应该使用%f而不是%d之类的内容。对于scanf也一样。

答案 3 :(得分:1)

如果您想接受浮点输入,请使用scanf(和printf%lf格式字符,而不是%d(用于整数)。< / p>

当前程序的行为未定义,因为scanf调用正在将整数写入float变量。此外,您在计划的顶部缺少include <stdio.h>。要捕获这些错误,请打开C编译器中的警告:

$ gcc so-scanf.c -Wall
so-scanf.c: In function ‘main’:
so-scanf.c:6:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
so-scanf.c:6:5: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
so-scanf.c:7:5: warning: implicit declaration of function ‘scanf’ [-Wimplicit-function-declaration]
so-scanf.c:7:5: warning: incompatible implicit declaration of built-in function ‘scanf’ [enabled by default]
so-scanf.c:7:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘double *’ [-Wformat]
so-scanf.c:9:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘double *’ [-Wformat]
so-scanf.c:11:5: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘double *’ [-Wformat]
so-scanf.c:13:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘double’ [-Wformat]