【小练习】程序设计基本概念:类型转换1

1.练习代码

#include "stdafx.h"
#include <iostream>
#include <string.h>
#include <conio.h>
#include <stdio.h>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	float a =1.0f;
	cout << (int)a << endl;
	cout << &a << endl;
	cout << (int&)a << endl;
	cout << boolalpha << ((int)a == (int&)a) << endl;
	float b = 0.0f;
	cout << (int)b << endl;
	cout << &b << endl;
	cout << (int&)b << endl;
	cout << boolalpha << ((int)b == (int&)b) << endl;
	return 0;
}

2.关键点分析

2.1类型转换过程

#include "stdafx.h"
#include <iostream>
#include <string.h>
#include <conio.h>
#include <stdio.h>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	float a =1.0f;
	cout << (int)a << endl;
	//float转换成int类型输出,值仍为1(测试环境中float和int都是4字节存储)
	cout << &a << endl;
	//取a变量的地址
	cout << (int&)a << endl;
	//取a变量的地址,将前sizeof(int),4个字节的值打印出来
	cout << boolalpha << ((int)a == (int&)a) << endl;
	//判断int类型a变量,与该地址的值前4字节的值是否相同,这里不相同,返回false
	float b = 0.0f;
	cout << (int)b << endl;
	//float转换成int类型输出,值仍为0(测试环境中float和int都是4字节存储)
	cout << &b << endl;
	//取b变量的地址	
	cout << (int&)b << endl;
	//取b变量的地址,将前sizeof(int),4个字节的值打印出来	
	cout << boolalpha << ((int)b == (int&)b) << endl;
	//判断int类型b变量,与该地址的值前4字节的值是否相同,这里不相同,返回true
	return 0;
}

2.2运行结果

【小练习】程序设计基本概念:类型转换1