在C++ Primer Plus中,第三章处理数据翻弄比较杂,从简单的命名规则讲到了类型转换。
在这里不做过多赘述,照例以几道课后习题来检验本章的内容。
1.编写一个小程序,要求用户使用一个整数指出自己的身高(单位为英寸),然后将身高转换为英尺。该程序使用下划线字符来指示输入位置,另外,使用一个const 符号常量来表示转换因子。
分析:该题有趣的地方在于要求使用下划线表示输入的位置,经分析,我们可以用转义字符/b与_结合实现。需要注意的是,该题需要使用const符号常量。
经查,1 ft=12 in。
code如下:
#include <iostream>
using namespace std;
int main()
{
const int hex = 12;
cout<<"Please input your height :___\b\b\b";//此处使用\b转义序列
int heightIn;
cin>>heightIn;
cout<<"inch"<<endl;
float heightFt;
heightFt=(float)heightIn/hex;//此处有一个类型转换的过程,因为是用int除以一个float,如果不转换类型会丢失精度。 此处采用强制转换。
cout<<"Your height is "<<heightFt<<" foot.";
}
2.编写一个程序,要求用户以度、分、秒的方式输入一个维度,然后以度为单位显示该维度。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, 51 minutes, 19 seconds =37.8553 degrees
分析:理解题意,六十进制。考察了const的使用与类型转换。
code:
#include <iostream>
using namespace std;
int main()
{
const int hex=60;//两个进制都是60,采用一个即可
cout<<" Enter a latitude in degrees, minutes, and seconds:"<<endl<<"First, enter the degrees:";
int deg;
cin>>deg;
//cout<<deg;这里无需再添加输出语句,因为输入的数据会留在屏幕上
cout<<"Next, enter the minutes:";
int min;
cin>>min;
cout<<"Finally, enter the seconds:";
int sec;
cin>>sec;
double nowDeg;
nowDeg=deg+(double)min/hex+(double)sec/(hex*hex);//强制类型转换
cout<<deg<<"degrees,"<<min<<"minutes,"<<sec<<"seconds = "<<nowDeg<<" degrees";
}
3.编写一个程序,要求用户输入全球当前的人口和美国当前的人口(或其他国家的人口)。将这些信息存储在longlong变量中,并让程序显示美国(或其他国家)的人口占全球人口的百分比。该程序的输出应与下面类似:
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.
分析:此题人口数目较大,要求使用long long类型存储。
需要注意的是,longl long类型相除可能产生比较大的数,所以需要使用long double 类型避免溢出。
且,long long类型实际上是一个整数型,需要进行类型转换。
code:
code:
#include <iostream>
using namespace std;
int main()
{
cout<< "Enter the world's population:";
long long worldNum;
cin>>worldNum;
cout<< "Enter the population of the US:";
long long USANum;
cin>>USANum;
long double percentage=( long double)USANum/worldNum*100;
//只需转换前者便完成了强制类型转换,后面可以不转换
//转化为百分数要乘以100
cout<<"The population of the US is "<<percentage<<"% of the world population.";
}