执行了下面一段代码为什么会有这样的结果?

来源:百度知道 编辑:UC知道 时间:2024/05/24 17:29:46
#include <iostream>
int main()
{char a;
short int c;
long d;
float b=7e4;
a=c=d=b;
std::cout<<a;
std::cout<<"\n";
std::cout<<c;
std::cout<<"\n";
std::cout<<d;
return 0;
}

结果是:
p
4464
70000
这是段类型转换的代码,能解释一下吗

首先,你要明白各种类型的变量占内存空间的大小。
char--1 Bytes;
short int--2 Bytes;
int=long int=float--4 Bytes;
double--8 Bytes;

代码中b是float,十进制70000=十六进制11170。即 00 01 11 70 。
因此将他赋值给d(long型)时,d的值就是0x11170,也就是十进制的70000;

再把d赋值给c(short int),由于c只有2 Bytes空间,只能取d的低2字节数据,即0x1170,十进制为4464;

再把c赋值给a(char型),由于a只有1 Byte空间,因此只能取c的低字节数据,即0x70给a,而0x70即十进制112,查ascii表可知,对应字符为小写p。

#include <iostream>
int main()
{char a;
short int c;
long d;
float b=7e4;//b=70000.0科学记数法
a=c=d=b; //70000 = 0x00011170(16进制)
std::cout<<a; //a=0x1170 = 4464 a是short占16位
std::cout<<"\n";
std::cout<<c; //c=0x70 = 'p' c是char占8位
std::cout<<"\n";
std::cout<<d; //d=0x11170 = 70000 d是long占32位
return 0;
}

楼上的不错
要注意的是
a=c=d=b;
等价于
d=b;//float转为long
c=d;//long转为short int
a=c;//short int转为char