-1

for example,

#include <stdio.h>

int main (void) {

    int x = 5;
    double y = 6;
    int z = x+y;

    printf("size of z = %d bytes",sizeof(z));

    return 0;
}

The output is 4 bytes, why doesn't it converted to double and takes 8 bytes of memory as a double.

4

5 回答 5

4

不,sizeof z永远都是sizeof(int)

当你这样做时:

int z = x+y;

的值x将被转换为double因为y是双倍的,但这不会改变x。并且x+y(type double) 的结果将被转换为int,并分配给z

于 2013-08-15T08:07:29.013 回答
0

阅读描述您的代码行为的注释:

#include <stdio.h>

int main (void) {

int x = 5;
double y = 6;
int z = x+y; // 5 (int, 4 bytes) + 6 (double, 8 bytes)
             // converting `int` to `double` when adding them ()
             // 5.0 (double, 8 bytes) + 6.0 (double, 8 bytes)
             // 11.0 (double, 8 bytes)
             // But! `z` is of type `int`, so it will not convert to `double`
             // Then 11.0 converts to 11 because `z`... is of type `int`! 
            /// read "Double-precision floating-point format" and you'll see why.
             // So,  z = 11 (`z` is of type `int`, so it's size is *4* bytes )
             // Here is your 4 bytes instead of 8! ;)

printf("size of z = %d bytes",sizeof(z));
return 0;

}

于 2013-08-15T08:15:15.120 回答
0

您已将 z 定义为整数。在执行“x+y”时,加法确实发生在双倍大小上,但在分配时会执行隐式转换并截断结果以适应 z 的大小。

于 2013-08-15T08:05:28.800 回答
0

您的输出是4因为您要声明int z. z将始终是 type int

即使表达式x+y的类型为doublebecause yis a double,该表达式也将被隐式转换为,int因为您尝试分配int给 and int

检查此代码:

#include <stdio.h>

int main()
{
    int x = 4;
    double y = 5;
    int z = x+y;

    printf( "%d %d \n", sizeof(z), sizeof( x + y ) );
    return 0;
}

输出将是4 8因为zis 的类型intx+y和type的表达式double例子

于 2013-08-15T08:34:30.833 回答
0

由于您声明z 为int,它将是int。并且每个可能的转换都将从任何类型转换为 int:

  int z = whatever (legal) formula you put here; 
  sizeof(z); /* <- 4 */

相反 x + y 的时间值是 double 最终转换为 int

  int x = 5;
  double y = 6;
  int z = x+y; /* x + y = 11.0 since y = 6.0; which is converted to 11*/
于 2013-08-15T08:10:58.817 回答