例如,
#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;
}
输出为 4 字节,为什么不将其转换为double并将 8 字节的内存作为double。
答案 0 :(得分:4)
不,sizeof z
始终为sizeof(int)
当你这样做时:
int z = x+y;
x
的值将转换为double
,因为y
是双倍的,但这不会改变x
。 x+y
(类型double
)的结果将转换为int
,并分配给z
。
答案 1 :(得分:0)
您已将z定义为整数。在执行“x + y”时,添加确实发生在双倍大小上,但在分配时执行隐式转换并截断结果以适合z的大小。
答案 2 :(得分: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*/
答案 3 :(得分: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;
}
答案 4 :(得分:0)
您的输出为4
,因为您声明int z
。 z
将始终为int
类型。
即使表达式x+y
的类型为double
,因为y
是double
,此表达式也会隐式转换为int
,因为您尝试将int
分配给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
,因为 z
的类型为int
,而x+y
的类型为double
。 Example