为什么x和y总是为0? [英] Why is x and y always 0 with a float?

查看:241
本文介绍了为什么x和y总是为0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  int main(void){
float x = 1;
float y = 2;
while(x x = x + 1;
y = y +1;
}
printf(x is%d \\\
,x);
printf(y是%d \ n,y);

$ / code>

我希望x和y增加到我们用完的位,但在这种情况下,似乎x和y总是0 ... ...正如其他人所说,你应该是使用%f 格式打印浮点数,而不是%d ,这是整数。还有%e ,它以科学记数法而不是固定记数法打印浮点数,还有%g ,它打印科学或固定,无论哪一个较短。

它打印为0的原因是因为浮动参数自动转换为双打当作为参数传递给variadic函数(也就是带有非特定数量参数的函数),比如 printf()。数字2和3(code> x y )的表示形式分别为0x4000000000000000和0x4008000000000000。按照 IEEE-754浮点转换计算器计算。 p>

在little-endian机器上(例如任何基于x86的机器),%d 修饰符抓取下一个4字节堆栈并将它们解释为一个整数。所以,当你传递float 2的时候,它会被转换成一个double 0x4000000000000000,在little-endian中是00 00 00 00 00 00 00 40.前四个字节是整数0,所以就是打印输出。 / b>

请注意,如果您在一条语句而不是两条语句中打印两个数字,则会得到一个更令人惊讶的结果:

  printf(x =%dy =%d \ n,x,y); 
//输出:x = 0 y = 1073741824

大多数编译器可以提醒你这些如果将警告级别设置得足够高,则会出现错误类型。使用GCC,您应该使用 -Wformat 选项(或 -Wall ,其中包括 -Wformat ),当你试图打印一个含有%d 的浮动数据时,它会发出警告。


int main(void){
    float x =1;
    float y =2;
    while (x<y){
        x = x +1 ;
        y = y +1;
}
    printf("x is %d\n", x);
    printf("y is %d\n", y);
}

I would expect x and y to increase to the point we run out of bits, but it seems like x and y is alway 0 in this case...

解决方案

As others have stated, you should be using the %f format to print floats, not %d, which is for integers. There is also %e, which prints the float in scientific notation instead of fixed notation, and there's also %g, which prints it in either scientific or fixed, whichever is shorter.

The reason why it prints as 0 is because float arguments automatically get converted to doubles when passed as arguments to variadic functions (that is, functions which take an unspecified number of arguments) such as printf(). The representations of the numbers 2 and 3 (the values of x and y) as doubles are 0x4000000000000000 and 0x4008000000000000 respectively, as calculated by the IEEE-754 Floating-Point Conversion calculator.

On little-endian machines (e.g. anything x86-based), the %d modifier grabs the next 4 bytes off the stack and interprets them as an integer. So, when you pass the float 2, it gets converted to a double as 0x4000000000000000, which in little-endian is 00 00 00 00 00 00 00 40. The first four bytes make the integer 0, so that's what is printed out.

Note that if you printed both numbers in one statement instead of two, you would get a more surprising result:

printf("x=%d y=%d\n", x, y);
// Output: x=0 y=1073741824

Most compilers can warn you about these types of errors if you set the warning level high enough. With GCC, you should compile with the -Wformat option (or -Wall, which includes -Wformat), and it will warn you when you try to print a float with %d by accident.

这篇关于为什么x和y总是为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆