【实训2-8】数据类型转换
(总分21)


 【实训目的】理解数据类型转换   

 

【第 1 步】实训内容介绍

实训内容介绍
自动类型转换
强制类型转换
实训结束

【Jitor 校验第 1 步】我已阅读实训内容介绍          // 送分题。直接点击。

 

【第 2 步】自动类型转换
 1、本实训使用项目 cpp2 中的 cpp2code.cpp 源代码文件,如果不存在,则先创建项目,然后创建源代码文件。 2、将下述代码复制到 cpp2code 中:
#include <iostream.h>
#include <typeinfo.h>

void main(void){
         int a1 = 2, a2 = 3;
         short b1 = 2, b2 = 3;
         char c1 = '2', c2 = 'c';
         double d1 = 2.1, d2 = 3.1;
         float f1 = 2.1;  // 这里有一个警告信息
         float f2 = 3.1f; // 没有警告,因为加了一个 f,表示是一个单精度浮点数

         cout << "short, char自动转换为int:\n";
         cout << "短整数相加的结果类型={" << typeid(b1 + b2).name() << "}\n";
         cout << "字符相加的结果类型={" << typeid(c1 + c2).name() << "}\n";

         cout << "\n不同类型相加:\n";
         cout << "整数加单精度的结果类型={" << typeid(a1 + f2).name() << "}\n";
         cout << "字符加双精度的结果类型={" << typeid(c1 + d2).name() << "}\n";
         cout << "单双精度相加的结果类型={" << typeid(f1 + d2).name() << "}\n";
}

 直接运行,对照代码和运行结果理解自动类型转换:
short, char自动转换为int:
短整数相加的结果类型={int}
字符相加的结果类型={int}

不同类型相加:
整数加单精度的结果类型={float}
字符加双精度的结果类型={double}
单双精度相加的结果类型={double}
Press any key to continue

【Jitor 校验第 2 步】          // (送分题)复制上面的代码到VC++ 6.0,保存并运行。点击。

 

【第 3 步】强制类型转换
 将下述代码复制到 cpp2code 中:
#include <iostream.h>
#include <typeinfo.h>

void main(void){
         cout.unsetf(ios::fixed);
         cout.precision(15); // 设置15位小数

         cout << "强制类型转换(精度损失)\n";
         double d = 1.123456789012345;
         float f = d; //
         cout << "d={" << d << "}\n";
         cout << "f={" << f << "}\n";

         cout << "\n强制类型转换(数据溢出)\n";
         int a = 7000000000; // 全世界人员70亿,超出整型的范围
         cout << "70亿={" << a << "}\n";
}
 根据教程【例2-7】(2)加上强制类型转换(这时将出现精度损失和溢出),代码见█████,运行结果如下:
强制类型转换(精度损失)
d={1.12345678901235}
f={1.12346}

强制类型转换(数据溢出)
70亿={-1589934592}
Press any key to continue
 对照代码和运行结果理解强制类型转换,看看精度损失了多少,溢出后数据变成了什么。

代码如下:
/*
#include <iostream.h>             // 从这一行开始复制。
#include <typeinfo.h>

void main(void){
     cout.unsetf(ios::fixed);
     cout.precision(15); // 设置15位小数

     cout << "强制类型转换(精度损失)\n";
     double d = 1.123456789012345;
     float f = (float)d; //
     cout << "d={" << d << "}\n";
     cout << "f={" << f << "}\n";

     cout << "\n强制类型转换(数据溢出)\n";
     int a = (int)7000000000; // 全世界人员70亿,超出整型的范围
     cout << "70亿={" << a << "}\n";
}                         // 一直复制到这一行结束。

*/
【Jitor 校验第 3 步】         // 复制上面的代码到VC++ 6.0,保存并运行。点击。

 

 

【第 4 步】测试题:

第 4 题 [理解溢出] 选择题:

 【回答第 4 题】                  // (65538的短整数值是:)2点击。

 

 

【第 5 步】实训总结

 本次实训学习了自动类型转换和强制类型转换,要理解在这个过程中出现的精度损失和溢出。  溢出将导致程序的混乱,必须时刻注意。 

【Jitor 校验第 5 步】我已阅读实训总结          // 送分题。直接点击

 

仍有疑问 ? 联系QQ 9429444(陈海云) : 返回首页