0

Possible Duplicate:
print the float value in integer in C language

I am trying out a rather simple code like this:

float a = 1.5;
printf("%d",a);

It prints out 0. However, for other values, like 1.4,1.21, etc, it is printing out a garbage value. Not only for 1.5, for 1.25, 1.5, 1.75, 1.3125 (in other words, decimal numbers which can be perfectly converted into binary form), it is printing 0. What is the reason behind this? I found a similar post here, and the first answer looks like an awesome answer, but I couldn't discern it. Can any body explain why is this happening? What has endian-ness got to do with t?

4

4 回答 4

2

you're not casting the float, printf is just interpreting it as an integer which is why you're getting seemingly garbage values.

Edit:

Check this example C code, which shows how a double is stored in memory:

int main()
{
    double a = 1.5;
    unsigned char *p = &a;
    int i;

    for (i=0; i<sizeof(double); i++) {
        printf("%.2x", *(p+i));
    }
    printf("\n");
    return 0;
}

If you run that with 1.5 it prints

000000000000f83f

If you try it with 1.41 it prints

b81e85eb51b8f63f

So when printf interprets 1.5 as an int, it prints zero because the 4 LSBs are zeros and some other value when trying with 1.41.

That being said, it is an undefined behaviour and you should avoid it plus you won't always get the same result it depends on the machine and how the arguments are passed.

Note: the bytes are reversed because this is compiled on a little indian machine which means the least significant byte comes first.

于 2012-11-01T17:06:31.233 回答
1

你不关心争论的提升。因为printf是一个可变参数函数,所以参数被提升:

C11 (n1570), § 6.5.2.2 函数调用
具有浮点类型的参数被提升为双精度。

因此printf尝试将您的double变量解释为整数类型。它会导致未定义的行为。只需添加一个演员:

double a = 1.5;
printf("%d", (int)a);
于 2012-11-01T17:10:33.333 回答
1

参数的不匹配printfundefined beahivour 类型转换a或使用%f

用这种方式

printf("%d",(int)a);

或者

printf("%f",a);
于 2012-11-01T17:10:42.863 回答
0

d 代表:decimal。所以,尽管如此,a 是浮点数/双精度数/整数/字符,.... 当您使用 : "%d" 时,C 将以十进制打印该数字。所以,如果 a 是整数类型(整数、长整数),没问题。如果 a 是 char :因为 char 是一种整数类型,所以,C 将以 ASCII 格式打印 char 的值。

但是,问题出现了,当a是float类型(float/double)时,只是因为如果a是float类型,C会有特殊的方式来读取这个,而不是十进制方式。所以,你会得到奇怪的结果。

为什么会有这个奇怪的结果?

我只是做一个简短的解释:在计算机中,实数由两部分表示:exponentmantissa。如果你说:这是一个实数,C 会知道哪个是指数,哪个是尾数。但是,因为你说:嘿,这是整数。指数部分和尾数部分没有区别->奇怪的结果。

如果您想准确理解,如何知道它将打印哪个整数(当然,您可以猜到)。您可以访问此链接:在 C 中表示内存中的 FLOAT 数

如果你不想得到这个奇怪的结果,你可以强制转换int为浮点数,所以,它会打印浮点数的整数部分。

 float a = 1.5;
   printf("%d",(int)a);

希望这有帮助:)

于 2012-11-01T17:14:39.653 回答