目录
介绍
本文是通过观看C++ Primer Plus(第六版)进行学习之后的分享 。只是分享第二章的七个练习题
编译及运行环境
我这里直接是在Ubuntu 12.04.05 版本上使用Vim 编辑器纯手敲代码(初学者推荐,记忆更加深刻);
前两章目录见下图
七个练习题如下图所示,其中第七个练习题,我加入了循环判断,可能不属于第二章知识
第二章属于基础练习题,都比较简单
简单掌握预编译命令,命名空间,函数的使用,甚至算上代码格式规范等即可
第一题
简单输出自己的名字,地址
#include <iostream>
using namespace std;
int main(){
cout << "My Name is programmer" << endl;
cout << "I am in shenzhen" << endl;
return 0;
}
第二题
有学习函数(也叫方法)的使用
//练习题2 编写一个C++程序,它要求用户输入一个以long为单位的距离,然后将它转换为码(一Long等于220码)
#include <iostream>
using namespace std;
int temp(int);
int main(){
cout << "请输入一个数" << endl;
int num;
cin >> num ;
cout << num << " Long = " << temp(num) << "码\n";
return 0 ;
}
int temp(int nums){
return nums*220;
}
第三题
#include <iostream>
using namespace std;
void funOne();
void funTwo();
int main(){
cout << "这是练习题三 " << endl;
funOne();
funOne();
funTwo();
funTwo();
return 0;
}
void funOne(){
cout << "Three blind mice" << endl;
}
void funTwo(){
cout << "See how they run" << endl;
}
第四题
有涉及到交互,这里可以对比第五题发现有啥不同之处
#include <iostream>
using namespace std;
int ageToMonth(int ages){
return ages*12;
}
int main(){
cout << "这里是练习题4 " << endl;
cout << "请输入你的年龄: \n";
int age;
cin >> age ;
cout << age << "岁包含" << ageToMonth(age) << "个月" << endl;
return 0;
}
/*int ageToMonth(int ages){
return ages*12;
}*/
第五题
#include <iostream>
using namespace std;
double tempTo(double);
int main(){
double temp;
cout << "Please enter a Celsius value:" << endl;
cin >> temp;
cout << temp << " degrees Celsius is " << tempTo(temp) << " degrees Fahrenheit. " << endl;
return 0;
}
double tempTo(double temp){
double hua = 1.8*temp +32.0;
return hua;
}
第六题
#include <iostream>
using namespace std;
double yearsTo(double);
int main(){
cout << "Enter the number of light years: " << endl;
double years;
cin >> years;
cout << years << " light years = " << yearsTo(years) << " astronomical units " << endl;
return 0;
}
double yearsTo(double year){
return year*63240;
}
第七题
这里有加入while 循环判断时间大小的参数,如果不对会一直循环重新输入三次,三次都不对的话则退出程序
#include <iostream>
using namespace std;
void addString(int,int);
int main(){
cout << "这是C++ primer Plus(第六版) 第二章节的最后一道练习题 \n" ;
cout << "Enter the number of hour: " << endl;
int a,b,c;
cin >> a;
while(a>24){
c++;
if(c>3){
cout << "重新输入三次错误,程序退出 \n";
return -1;
}
cout << "时间不能大于24 ,请重新输入一个数 : " << endl;
cin >> a ;
}
cout << "Enter the number of minutes" << endl;
cin >> b;
while(b>60 || b<0){
cout << "分钟数不能大于60小于0 ,请重新输入 :" << endl;
cin >>b;
}
addString(a,b);
return 0;
}
void addString(int a,int b){
cout << "Time : " << a << ":" << b <<endl;
}
持续学习中,谢谢看到这篇文章的人,喜欢的话,点个赞再走,嘿嘿嘿