C++ Primer Plus 第二章之编程练习题

2.1 显示姓名和地址

#include<iostream>
using namespace std;
int main(){
 cout<<"姓名:小明 地址:中国"<<endl; 
 return 0;
} 

2.2 以long为单位进行220码的转换

#include<iostream>
using namespace std;
int convert(int llong)
{
 return llong*220;
} 
int main()
{
 int llong;
 cin>>llong;
 cout<<"以long为单位进行转换\n"<<"有"<<llong<<"个long,"<<"有"<<convert(llong)<<"码"<<endl;
 return 0;
}

2.3 使用3个自定义函数

// 2.3 使用3个自定义函数
#include<iostream>
using namespace std;
void fun1()
{
	cout<<"Three blind mice"<<endl;
	return ;
} 

void fun2()
{
	cout<<"See how they run"<<endl;
	return ;
} 

int main()
{
	fun1();
	fun1();
	fun2();
	fun2();
	return 0;
}

2.4 输入年龄显示包含几个月

//2.4 输入年龄显示包含几个月

#include<iostream>
using namespace std;

int main()
{
	int year;
	cin>>year;
	cout<<"年龄是:"<<year<<"岁,一共有"<<year*12<<"月"; 
	return 0;
} 

2.5 摄氏温度值转换为华氏温度值

// 2.5 摄氏温度值转换为华氏温度值

#include<iostream>
using namespace std;

float convert(float she){
	return 1.8*she+32.0;
}
int main()
{
	float she;
	cout<<"输入摄氏温度值:";
	cin>>she;
	cout<<"转换后的华氏温度:"<<convert(she)<<endl; 
	return 0;
} 

2.6 光年 天文单位转换

//2.6 光年 天文单位转换
//错误提醒:不要顺手就给变量定float和int型要充分考虑所需的数据类型 
#include <iostream>
using namespace std;

double convert(double light)
{
	return light*63240;
} 
int main() 
{
	double light;
	cout<<"输入光年:";
	cin>>light;
	cout<<"天文单位"<<convert(light)<<endl;
	return 0;
	 
}

2.7 显示小时和分钟数

// 2.7 显示小时和分钟数

#include<iostream>
using namespace std;

void display(double hour,double minu)
{
	cout<<"Time:"<<hour<<":"<<minu;
}
int main()
{
	double hour,minu;
	cout<<"Enter the number of hours:";
	cin>>hour;
	cout<<"Enter the number of minutes:";
	cin>>minu;
	display(hour,minu);
	return 0;
} 

总结

  1. 错误提醒:不要顺手就给变量定float和int型,要充分考虑所需的数据类型,比如有时候是需要double而不是int,或float。

  2. 第二章也只是粗略的看,因为感觉好像都是一些了解性的东西,没有认真看,不知道会不会打脸,不知道到后面是不是会很重要,需要特别注意。

  3. 知道为什么要#include,cin cout包含在其中,知道为什么要用using namespace std;这个名称空间。(其实理解的也不是很深)

  4. 好厚的书!继续学!

发布了9 篇原创文章 · 获赞 0 · 访问量 1804

猜你喜欢

转载自blog.csdn.net/weixin_46021869/article/details/104027147