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

相关文章:

  • 2021-08-27
  • 2021-10-27
  • 2021-12-07
  • 2021-11-03
  • 2022-02-11
  • 2022-01-20
  • 2021-06-29
猜你喜欢
  • 2021-05-01
  • 2021-09-21
  • 2021-04-22
  • 2022-12-23
  • 2021-12-24
  • 2022-02-28
  • 2021-07-21
相关资源
相似解决方案