本章内容包括:
1. C++变量的命名规则 | 2. C++内置的整型——unsigned long、long、unsigned in、int 、unsigned short、short、char、unsigned char、signed char和bool |
3. C++11新增的整型:unsigned long long 和 long long | 4. 表示各种整型的系统限制的climits文件 |
5. 各种整型的数字字面值(常量) | 6. 使用const限定符来创建符号常量 |
7. C++内置的浮点类型:float、double和long double | 8. 表示各种浮点类型的系统限制的cfloat文件 |
9. 各种浮点类型的数字字面值 | 10. C++的算术运算符 |
11. 自动类型转换 | 12. 强制类型转换 |
内置的基本类型分两组,基本类型和复合类型
基本类型为整型、浮点数
复合类型为数组、字符串、指针和结构
3.1 简单变量
使用&检索变量内存地址
变量名遵循命名规则并具有含义
通过使用不同的位来存储值
short至少16位 | int至少与short一样长 |
long至少32位,且至少与int一样长 | long long至少64位,且至少与long一样长 |
程序清单3.1 limits.cpp
// limits.cpp -- some integer limits
#include <iostream> //头文件中定义限制符号的位数和值
#include <climits> //其他符号常量表见P41
int main()
{
using namespace std;
int n_int = INT_MAX;
short n_short = SHRT_MAX;
long n_long = LONG_MAX;
long long n_llong = LLONG_MAX;
cout << "int is " << sizeof (int) << " bytes." << endl;
cout << "short is " << sizeof n_short << " bytes." << endl;
cout << "long is " << sizeof n_long << " bytes." << endl;
cout << "long long is" << sizeof n_llong << " bytes." << endl;
cout << endl;
cout << "Maximum values:" << endl;
cout << "int: " << n_int << endl;
cout << "short: " << n_short << endl;
cout << "long: " << n_long << endl;
cout << "long long: " << n_llong << endl << endl;
cout << "Minimum int value = " << INT_MIN << endl;
cout << "Bits per byte = " << CHAR_BIT << endl;
cin.get();
return 0;
}
头文件climits中包含各种符号常量 P41
sizeof对类型名使用需加(),对变量名()可选
初始化将赋值与声明合在一起 int n_int = INT_MAX;
初始化可以用常量,已定义变量,所有值都已知表达式
大括号赋值可以使用=,也可不用 int emus{7}; int rheas = {12};,可为空,初始化为零
无符号类型可以为非负值增加表示范围, unsigned short change; unsigned int rovert;
#define ZERO 0 表示定义ZERO为0
程序清单3.2 exceed.cpp
// exceed.cpp -- exceeding some integer limits
#include <iostream> //演示如何使用无符号类型,类型最大值最小值增加减少后的溢出
#define ZERO 0 //定义为0
#include <climits>
int main()
{
using namespace std;
short sam = SHRT_MAX;
unsigned short sue = sam;
cout << "Sam has " << sam << " dollars and Sue has " << sue;
cout << " dollars deposited." << endl
<< "Add $1 to each account." << endl << "Now ";
sam = sam + 1;
sue = sue + 1;
cout << "Sam has " << sam << " dollars and Sue has " << sue;
cout << " dollars deposited.\nPoor Sam!" << endl;
sam = ZERO;
sue = ZERO;
cout << "Sam has " << sam << " dollars and Sue has " << sue;
cout << " dollars deposited." << endl << "Now ";
sam = sam - 1;
sue = sue - 1;
cout << "Sam has " << sam << " dollars and Sue has " << sue;
cout << " dollars deposited." << endl << "Lucky Sue!" << endl;
cin.get();
return 0;
}
一般选择int,自然长度,计算机处理起来效率最高的长度
C++用三种基数来书写整数
程序清单3.3 hexoct.cpp
// hexoct1.cpp -- shows hex and octal literals
#include <iostream> //演示三种基数的书写方式
int main()
{
using namespace std;
int chest = 42;
int waist = 0x42;
int inseam = 042;
//默认状态cout以十进制格式显示整数
cout << "Monsieur cuts a striking figure!\n";
cout << "chest = " << chest << " (42 in decimal1)\n";
cout << "waist = " << waist << " (0x42 in hex)\n";
cout << "inseam = " << inseam << " (042 in octal)\n";
cin.get();
return 0;
}
默认情况,cout以十进制格式显示整数,而不管这些整数在程序中是如何书写的
头文件iostream提供控制符dec、hex和oct,用于只是cout显示十进制、十六进制和八进制整数
默认十进制,在修改格式之前,之前格式一直有效
程序清单3.4 hexoct2.cpp
// hexoct2.cpp -- display values in hex and octal
#include <iostream> //演示cout通过控制符显示整数不同格式
using namespace std;
int main()
{
//using namespace std; //不是在主函数外边定义了么,还写干嘛
int chest = 42;
int waist = 42;
int inseam = 42;
cout << "Monsieur cuts a striking figure!" << endl;
cout << "cheat = " << chest << " (decimal for 42)" << endl;
cout << hex;
cout << "waist = " << waist << " (hexadecimal for 42)" << endl;
cout << oct;
cout << "inseam = " << inseam << " (octal for 42)" << endl;
cin.get();
return 0;
}
除非有其他理由,否则C++将整型常量存储为int类型
后缀,表示类型 P47
char类型为存储字符
程序清单3.5 chartype.cpp
// chartype.cpp -- the char type
#include <iostream> //演示使用char类型
int main()
{
using namespace std;
char ch;
cout << "Enter a character: " << endl;
cin >> ch;
cout << "Hola! ";
cout << "Thank you for the " << ch << " character." << endl;
cin.get();
cin.get();
return 0;
}
书写字符字面值,将字符用单引号括起,'M',对字符串时使用双引号
程序清单3.6 morechar.cpp
// morechar.cpp -- the char type and int type conrtrasted
#include <iostream>
int main()
{
using namespace std;
char ch = 'M'; //M数值编码
int i = ch; //i也是77
cout << "The ASCII code for " << ch << " is " << i << endl;
// 值的类型将引导
cout << "Add one to the character code:" << endl;
ch = ch + 1;
i = ch;
cout << "The ASCII code for " << ch << " is " << i << endl;
cout << "Displaying char ch using cout.put(ch): ";
cout.put(ch);
cout.put('!');
cout << endl << "Done" << endl;
cin.get();
return 0;
}
成员函数cin.put(); 显示一个字符
char ch = 'M'; 赋值为数字 可进行运算
C++转义序列编码 P50
换行可以采用多种方法,可以嵌入到较长字符串中
程序清单3.7 bondini.cpp
// bondini.cpp -- using escape sequences
#include <iostream> \\演示转义序列的应用
int main()
{
using namespace std;
cout << "\aOperation \"HyperHype\" is now activated!\n"; // \a振铃
cout << "Enter your agent code:________\b\b\b\b\b\b\b\b";
long code;
cin >> code;
cout << "\aYou entered " << code << "...\n";
cout << "\aCode verified! Proceed with Plan Z3!\n";
cin.get();
cin.get();
return 0;
}
char也有 signed char和unsigned char
wcha_t 宽字符类型 iostream提供了相似的工具——wcin和wcout处理wchar_t
C++11新增char16_t和char32_t 都无符号
bool 布尔类型 任何数字值或指针值都可以被隐式转换为bool值,任何非零值都被转换为true,而零被转换为false
3.2 const限定符
const限定符 在声明时进行初始化 将值固定 遵循作用域
3.3 浮点数
浮点数能表示小数,有两种书写方式 小数点 12.456 E表示法 大小写都可以 正负为乘10除10 2.56E+6 不能有空格
程序清单3.8 floating.cpp
// floatnum.cpp -- floating-point types
#include <iostream> //演示float和double的区别
int main()
{
using namespace std;
cout.setf(ios_base::fixed, ios_base::floatfield); //显示结尾的0
float tub = 10.0 / 3.0;
double mint = 10.0 / 3.0;
const float million = 1.0e6;
cout << "tub = " << tub;
cout << ", a million tubs = " << million * tub;
cout << ",\nand ten million tubs = ";
cout << 10 * million * tub << endl;
cout << "mint = " << mint << " and a miliion mints = ";
cout << million * mint << endl;
cin.get();
return 0;
}
cout输出会删除结尾的0 如333.5000 输出 333.5 使用cout.setf()将覆盖这种行为
程序默认浮点常量存储为double, 如果要存成float 常量后代f或F 1.234F
浮点可以表示整数的值,同时运算速度比整数运算慢,精度降低
程序清单3.9 fltadd.cpp
// fltadd.cpp -- precision problems with float
#include <iostream> //演示C++运算符使用
int main()
{
using namespace std;
float a = 2.34E+22f;
float b = a + 1.0f;
cout << "a = " << a << endl;
cout << "b - a = " << b - a << endl;
cin.get();
return 0;
}
3.5 C++运算符
C++运算符,加减乘除求模 正常运算
程序清单3.10 arith.cpp
// arith.cpp -- some C++ arithmetic
#include <iostream
int main()
{
using namespace std;
float hats, heads;
cout.setf(ios_base::fixed, ios_base::floatfield);
cout << "Enter a number: ";
cin >> hats;
cout << "Enter another number: ";
cin >> heads;
cout << "hats = " << hats << "; heads = " << heads << endl;
cout << "hats + heads = " << hats + heads << endl;
cout << "hats - heads = " << hats - heads << endl;
cout << "hats * heads = " << hats * heads << endl;
cout << "hats / heads = " << hats / heads << endl;
cin.get();
cin.get();
return 0;
}
float,C++只保证6位有效 需要更高的精度使用double和long double
程序清单3.11 divide.cpp
// divide.cpp -- integer and floating-point division
#include <iostream>
int main()
{
using namespace std;
cout.setf(ios_base::fixed, ios_base::floatfield); //ios_base::fixed是设置cout为定点输出格式
//ios_base::floatfield是设置输出时按浮点格式,小数点后有6位数字
cout << "Integer division: 9/5 = " << 9 / 5 << endl;
cout << "Floating-point division: 9.0/5.0 = ";
cout << 9.0 / 5.0 << endl;
cout << "Mixed division: 9.0/5 = " << 9.0 / 5 << endl;
cout << "double constants: le7/9.0 = ";
cout << 1.e7f / 9.0f << endl;
cin.get();
return 0;
}
使用相同的符号进行多种操作叫做运算符重载
程序清单3.12 modulus.cpp
// modulus.cpp -- uses % operator to convert 1bs to stone
#include <iostream> //求模运算演示
int main()
{
using namespace std;
const int Lbs_per_stn = 14;
int lbs;
cout << "Enter your weight in pounds: ";
cin >> lbs;
int stone = lbs / Lbs_per_stn;
int pounds = lbs % Lbs_per_stn;
cout << lbs << " pounds are " << stone
<< " stone, " << pounds << " pound(s).\n";
cin.get();
cin.get();
return 0;
}
C++允许将一种算术类型的值赋给另一种算术类型的变量时,C++将对值进行转换
数据转换可能会出现多种情况的数据丢失
C++11中,{}初始化被称为列表初始化
当运算涉及两种类型时,较小的类型将被转换为较大的类型
C++转换校验表 P64
在将参数传递时,C++将float参数提升为double
C++允许通过强制类型转换机制显式地进行类型转换
将thorn中的int值新转换出一个long值 两种方法1.(long) thorn (typeName) value 2.long (thorn) typeName (value)
C++还引入了4个强制类型转换运算符, 后补
现在学了其中1个 static_cast<typeName> (value) 将值本身从一种数据类型 强项转换成另一种
程序清单3.13 assign.cpp
// init.cpp -- type changes on initialization
#include <iostream> //演示前边介绍的三种强制转换方式
int main()
{
using namespace std;
cout.setf(ios_base::fixed, ios_base::floatfield); //float输出
float tree = 3;
int guess(3.9832);
int debt = 7.2E12;
cout << "tree = " << tree << endl;
cout << "guess = " << guess << endl;
cout << "debt = " << debt << endl;
cin.get();
return 0;
}
当运算涉及两种类型时,较小的类型将被转换为较大的类型
C++转换校验表 P64
在将参数传递时,C++将float参数提升为double
C++允许通过强制类型转换机制显式地进行类型转换
将thorn中的int值新转换出一个long值 两种方法1.(long) thorn (typeName) value 2.long (thorn) typeName (value)
C++还引入了4个强制类型转换运算符, 后补
现在学了其中1个 static_cast<typeName> (value) 将值本身从一种数据类型 强项转换成另一种
程序清单3.14 typecast.cpp
// typecast.cpp -- forcing type changes
#include <iostream> //演示前边介绍的三种强制转换方式
int main()
{
using namespace std;
int auks, bats, coots; //声明三个整形变量
auks = 19.99 + 11.99;
bats = (int) 19.99 + (int) 11.99;
coots = int (19.99) + int (11.99);
cout << "auks = " << auks << ", bats = " << bats; //31 30
cout << ", coots = " << coots << endl; //30
char ch = 'Z';
cout << "The code for " << ch << " is ";
cout << int(ch) << endl;
cout << "Yes, the code is ";
cout << static_cast<int>(ch) << endl; //将字符型char强行转换为int 输出Z的ASCII
cin.get();
return 0;
}
auto n = 100; 用auto而不指定变量的类型,编译器将把变量的类型设置成与初始值相同
编程练习
1. 编写一个小程序。要求用户使用一个整数指出自己的身高(单位为英寸),然后将身高转换为英尺和英寸。该程序使用
下划线字符来指示输入位置。另外,使用一个const符号常量来表示转换因子。
// high.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "请输入您的身高(英尺):____\b\b\b\b";
int high;
cin >> high;
const int CF = 12;
cout << "您的身高是" << high / 12 << "英尺,"
<< high % 12 << "英寸" << endl;
cin.get();
cin.get();
return 0;
}
2. 编写一个小程序,要求以几英尺几英寸的方式输入其身高,并以磅为单位输入其体重。(使用3个变量来存储这些信息。)该程序报告其BMI(Body Mass Index,体重指数)。为了计算BMI,该程序以英寸的方式指出用户的身高(1英尺为12英寸),并将 以英寸为单位的身高转换为以米为单位的身高(1英寸=0.0254米)。然后,将以磅为单位的体重转换为以千克为单位的体重(1千克= 2.2磅)。最后,计算相应的BMI——体重(千克)除以身高(米)的平方。用符号常量表示各种转换因子。
// BMI.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "请输入您的身高(英尺英寸方式):";
int h_ft;
int h_in;
cin >> h_ft >> h_in;
cout << "请输入您的体重(磅):";
double i;
cin >> i;
const int CF_ftin = 12;
const double CF_inm = 0.0254;
const double CF_kgi = 1 / 2.2;
cout << "您的BMI是:" << (i * CF_kgi) / (((h_ft * CF_ftin) + h_in) * CF_inm);
cin.get();
cin.get();
return 0;
}
3. 编写一个程序,要求用户以度、分、秒的方式输入一个纬度,然后以度为单位显示该纬度。1度为60分,1分等于60秒,
请以符号常量的方式表示这些值。对于每个输入值,应使用一个独立的变量存储它。下面是该程序运行时的情况:
Enter a latitude in degrees , minutes, and seconds: |
First , enter the degrees: 37 |
Next , enter the minutes of arc: 51 |
Finally, enter the seconds of arc 19; |
37 degrees , 51minutes , 19 seconds = 37.8553 degrees |
// en.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "Enter a latitude in degree, minutes, and seconds:" << endl;
int d;
cout << "First, enter the degrees: ";
cin >> d;
int m;
cout << "Next, enter the minutes of arc: ";
cin >> m;
int s;
cout << "Finally, enter the seconds of arc: ";
cin >> s;
const double CF = double(1) / double(60); //需做浮点数
cout << d << " degrees, " << m << " minutes, " << s << " seconds = "
<< (s * CF + m) * CF + d << " degrees";
cin.get();
cin.get();
return 0;
}
4. 编写一个程序,要求用户以整数方式输入秒数(使用long或long long变量存储),然后以天、小时、分钟和秒的方式
显示这段时间。使用符号常量来表示每天有多少小时、每小时有多少分钟一集每分钟有多少秒。该程序的输出应与下列类似:
Enter the number of seconds: 31600000 |
31600000 seconds = 365 days, 17 hours , 46 minutes , 40 seconds |
// time.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "Enter the number of seconds:";
long seconds;
cin >> seconds;
const int CF_SM = 60;
const int CF_MH = 60;
const int CF_HD = 24;
int day = seconds / CF_SM / CF_MH / CF_HD;
int hour = seconds / CF_SM / CF_MH % CF_HD;
int minutes = seconds / CF_SM % CF_MH;
cout << seconds << " seconds = " << day << " days, "
<< hour << " hours, "
<< minutes << " minutes, "
<< seconds % CF_SM << " seconds"
<< endl;
cin.get();
cin.get();
return 0;
}
5. 编写一个程序,要求用户输入全球当前的人口和美国当前的人口(或其他国家的人口)。将这些信息存储在long long变量
中,并让程序显示美国(或其他国家)的人口占全球人口的百分比。该程序的输出应与下面类似:
Enter the world's population: 6898758899 |
Enter the population of the US: 310783781 |
The population of the US is 4.50492% of the world population. |
// US_Population.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "Enter the world's population: ";
long long W_Population;
cin >> W_Population;
cout << "Enter the population of the US: ";
long long U_Population;
cin >> U_Population;
cout << "The population of the US is "
<< ((double)U_Population / (double)W_Population) * 100 //有别的方法么
<< "% of the world population." << endl;
cin.get();
cin.get();
return 0;
}
6. 编写一个程序,要求用户输入驱车里程(英里)和使用汽油量(加仑),然后指出汽车耗油量为一加仑的里程。如果愿意, 也可以让程序要求用户以公里为单位输入距离,并以升为单位输入汽油量,然后指出欧洲风格的结果——即每100公里的耗油量(升)
// petrol.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "请输入行驶里程(英里)和使用汽油量(加仑):";
double mile;
double petrol;
cin >> mile >> petrol;
cout << "汽车耗油量为一加仑的里程为:" << mile / petrol << "英里" << endl;
cin.get();
cin.get();
return 0;
}
//不愿意
7. 编写一个程序,要求用户按欧洲风格输入汽车的耗油量(每100公里消耗的汽油量(升)),然后将其转换为美国风格的耗油量——每加仑多少英里。注意,除了使用不同的单位计量外,美国方法(距离/燃料)与欧洲方法(燃料/距离)相反。100公里 等于62.14英里,1加仑等于3.875升。因此,19mpg大约合12.41/100km,127mpg大约合8.71/100km。
// en.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "请输入行每100公里消耗的汽油量(升):";
double L;
cin >> L;
const double M_To_K = 62.14;
const double J_To_L = 3.875;
cout << "美国风格的耗油量:" << (M_To_K * J_To_L) / L
<< " 加仑每英里" << endl;
cin.get();
cin.get();
return 0;
}