C++之处理数据
来源:互联网 发布:美国队长身材 知乎 编辑:程序博客网 时间:2024/06/05 13:23
在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.";}
//该章节对于数据类型这一章节讲的比较深,但不够浅显,也没有烯烃完整列举出来各种数据类型,需要下去补课。
//另外不得不吐槽这个老编辑器太难用了,各种莫名其妙的bug。新编辑器又没找到在哪儿编辑已发表的文章。
- C 语言详解 之 持续处理数据
- C#DataSet处理数据
- C++之处理数据
- 【C#】之字符串处理
- nodejs之处理表单数据
- springmvc之处理模型数据
- 数据挖掘之数据归一化处理
- objective-c之错误处理
- objective-c之文件处理
- springmvc之处理模型数据之map
- springmvc之处理模型数据之ModeAndView
- C语言处理文件中数据
- C#,Excel数据的导入、处理、导出
- 数据封装和处理--C语言
- 《C Primer Plus 》--C++处理数据-变量
- Unity (C#) 使用 LitJson 处理 JSON 数据
- Unity (C#) 使用 LitJson 处理 JSON 数据
- C#(4)-------处理/Date(1502326189000)/格式数据
- python 常用模块的使用
- 基本正则表达式与扩展正则表达式
- web前端面试题汇总(一)
- tomcat 8配置HTTPS
- 650. 2 Keys Keyboard
- C++之处理数据
- html css
- webpack使用小技巧
- 抽象基类和纯虚函数
- POJ3261 Milk Patterns(后缀数组,二分)
- 玲珑学院OJ 1152-Expected value of the expression(概率DP)
- Win10 配置Python开发环境
- J
- framework自动化合并