第七章 简单数据类型
7.1常量复习
常量定义:
1)const 类型 标识符=常量;
2)#define 标识符 替换文本
例子:
1) const float PI=3.14159;
2) #define PI 3.14159;
7.2数值数据类型的内部表示
7.2.1数据类型的定点表示和浮点表示
float类型可以存储小数,并且数值范围远大于整型。
7.2.2整型
整型分为长整型和短整型
短整型的长度不能超过int类型
int类型的长度不能超过长整型
7.2.3浮点类型
浮点类型:float ,double,long double.
7.2.4数值型值常量的数据类型
7.2.5整型和浮点类型的取值范围
7.2.6数值误差
表示误差:用有限的位数来表示实数时发生的误差
消去误差:两个数量级相差很大的操作数进行算术运算而产生的误差,消去较小的数。
算术下溢:将非常小的计算结果表示为0的错误。
算术上溢:试图表示非常大的计算结果时产生的错误。
7.2.7混合类型:类型提升
7.2.8类型转换
7.2.9强制类型转换
7.3字符数据和函数
例子:ASCLL码排序序列程序实例
#include<iostream>
using namespace std;
int main()
{
const int MIN=32; //最小的数值代码
const int MAX=126; //最大的数值代码
char nextChar; //输出-下一个代码的字符形式
//显示字符序列
for(int nextCode=MIN;nextCode<=MAX;nextCode++){
nextChar=char(nextCode);
cout<<nextChar;
if(nextChar=='Z')
cout<<endl;
}
return 0;
}
7.4布尔类型数据和逻辑表达式
7.4.1逻辑表达式求补
如何求一个复合逻辑表达式的补:
1)写出每个简单逻辑表达式的补。
2)分别把每个“&&”改成“||”,把每个“||”改成“&&”。
7.4.2布尔类型函数
7.4.3布尔类型数据的输入与输出
例子:moreBills函数
//如果使用者有更多比尔去付返回正确
bool moreBills()
{
char answer; //存储使用者的答案
do{
cout<<"Any more bills(Y/N): ";
cin>>answer;
answer=toupper(answer); //去大写
}while(answer!='Y'&&answer!='N');
return (answer=='Y');
}
7.5枚举类型
枚举类型:用户自定义类型,带有一个该类型的值的列表。
枚举元素:在枚举类型中定义的一个标识符。
枚举类型声明
格式: enum 枚举类型名{枚举元素列表};
例子:enum classId{freshman,sophomore,junior,senior};
7.5.1字符作为枚举元素值
因为字符也有整型值,所以可以用字符常量去指定一个枚举元素。
7.5.2枚举类型的比较
当枚举类型被声明后,枚举类型的枚举元素之间的次序关系是固定的。
7.5.3整数类型之间的差别
每一种整数类型的声明是不同的。
7.5.4读写枚举类型值
例子:显示color类型值的函数
void writeColor(color thisColor) //输入:color作为一个字符串显示
{
//显示color作为字符串的值
switch(thisColor)
{
case red:
cout<<"red ";
break;
case green;
cout<<"green ";
break;
case blue;
cout<<"blue ";
break;
case yellow;
cout<<"yellow ";
break;
default:
cout<<"*** ERROR: Invalid color value."<<endl;
}
}
例子:读color类型值的函数
color readColor()
{
char colorChar; //数据字符的存储
//持续读程序直到数据字符有效
do{
cout<<"Enter first letter of color(R,G,B,or Y): ";
cin>>colorChar;
colorChar=toupper(colorChar); //去大写
//如果有效字符可读返回颜色的值
switch(colorChar)
{
case 'R':return red;
case 'G':return green;
case 'B':return blue;
case 'Y':return yellow;
default :cout<<"Try again!"<<endl;
}//结束switch
}while(true);
}
7.5.5程序风格–在switch语句中使用return语句
例子: 使用枚举类型color
#include<iostream>
using namespace std;
enum color{red,green,blue,yellow};
//函数类型
void writeColor(color);
color readColor();
int main()
{
color eyeColor,hairColor;
cout<<"Reading eye color"<<endl;
eyeColor==readColor();
cout<<endl<<"Reading hair color"<<endl;
hairColor=readColor();
cout<<endl<<"Eye color is ";
writeColor(eyeColor);
cout<<",hair color is ";
writeColor(hairColor);
cout<<endl;
return 0;
}//发送作用函数readColor和writeColor here.
7.5.6枚举类型声明语句的放置位置
例子:读取month类型值的函数
month readMonth()
{
int monthValue; //存储整数数据
//读一个正确的整数
cout<<"Reading month"
monthValue=getIntRange(1,12);
return (month(monthValue));
}