C++ primer plus复习题及练习程序答案第二章

时间:2023-02-27 14:56:13

第二章:

复习题:

1. 函数

2. 在最终编译之前,使用iostream中的内容替换该编译指令。

3. 程序可以使用std空间的定义,如cout或cin。

4. cout<<"Hello,world\n";或cout<<"Hello,world"<<endl;

5. int cheeses;

6.cheeses = 32;

7. cin>>cheeses;

8.cout<<"We have"<<cheeses<<"varieties of cheeses"<<endl;

9.int froop (double t);函数froop有返回值,且返回类型为int,函数参数类型为double。

  void rattle (int n);函数rattle没有返回值,参数类型为int。

  int prune(void);函数有返回值,且返回类型为int,没有参数。

10. 当函数返回类型为void时,不必使用return。

11.原因是程序中没有using namespace std语句。

编程练习

2.1
#include <iostream>
using namespace std;
int main(void)
{
	cout<<"name:DONGBYG"<<"Liaoning\n";
	return 0;
}
2.2 long2ma
#include<iostream>
using namespace std;
main()
{
	double Long,Ma;
	cin>>Long;
	Ma = 220*Long;
	cout<<Long<<"Long = "<<Ma<<"Ma\n";
	return 0;
}
2.3
#include<iostream>
using namespace std;
void mice();
void see();
int main()
{
	mice();
	mice();
	see();
	see();
	return 0;
}
void mice()
{
	cout<<"Three blind mice"<<endl;
}
void see()
{
	cout<<"See how they run"<<endl;
}
2.4
#include<iostream>
using namespace std;
int main()
{
	int age,month;
	cout<<"enter your age:";
	cin>>age;
	month = 12*age;
	cout<<"your age"<<age<<"="<<month<<"months"<<endl;
}

2.5
#include<iostream>
using namespace std;
double she2hua(double t);
int main()
{
	double she,hua;
	cout<<"Please enter a Celsius value:";
	cin>>she;
	hua = she2hua(she);
	cout<<"\n"<<she<<" degree Celsius is "<<hua<<" degrees Fahrenheit.\n";
    return 0;
}
double she2hua(double t)
{
	double n;
	n = 1.8*t+32.0;
	return n;
}
2.6
#include<iostream>
using namespace std;
double guang2tian(double t);
int main()
{
	double guang,tian;
	cout<<"Enter the number of light years:";
	cin>>guang;
	tian = guang2tian(guang);
	cout<<"\n"<<guang<<" light years = "<<tian<<" astronomical units.\n";
    return 0;
}
double guang2tian(double t)
{
	double n;
	n = 63240*t;
	return n;
}
2.7
#include<iostream>
using namespace std;
void showtime(int h,int m);
int main()
{
	int hours,minutes;
	cout<<"Enter the number of hours:";
	cin>>hours;
	cout<<"\nEnter the number of minutes:";
	cin>>minutes;
	showtime(hours,minutes);
    return 0;
}
void showtime(int h,int m)
{
	cout<<"\nTime :"<<h<<":"<<m<<endl;
}