C++ premier plus 第六版 编程练习解答(第二章)

1.编写C++程序显示姓名及地址

#include<iostream>
int main(void)
{
	using namespace std;
	cout << "name";
	cout << endl;
	cout << "address";
	cout << endl;
	return 0;
}

2.编写一个C++程序,它要求用户输入一个以long为单位的距离,然后将它转换为码(一long等于220码)

#include<iostream>
int main(void)
{
	using namespace std;
	int distance1,distance2;
	cout << "请输入以long为单位的距离" << endl;
	cin >> distance1;
	distance2 = 220 * distance1;
	cout << distance1 << "long=" << distance2 << "码" << endl;
	return 0;
}

3.编写一个C++程序,它使用3个用户定义的函数(包括mian()),并生成下面的输出:

Three blind mice
Three blind mice
See how they run
See how they run
其中一个函数要调用两次,该函数生成前两行;另一个函数也被调用两次并生成其余的输出。

#include<iostream>
using namespace std;

void mice(void);
void run(void);

int main(void)
{
	mice();
	mice();
	run();
	run();
	return 0;
}
void mice(void)
{
	cout << "Three blind mice" << endl;
}
void run(void)
{
	cout << "See how they run" << endl;
}

4.编写一个程序,让用户输入其年龄,然后显示该年龄包含多少个月。

#include<iostream>
int main()
{
	using namespace std;
	int year,month;
	cout << "Enter your age:";
	cin >> year;
	month=12*year;
	cout << "该年龄包含" << month << "个月"return 0;
}

5.编写一个程序,其中的main()调用一个用户定义的函数(以摄氏温度为参考值,并返回相应的华氏温度值)。

与第四题类似,但需运用函数知识。

#include<iostream>

float change(float celsius);

int main()
{
	using namespace std;
	float celsius,fahrenheit;
	cout << "Please enter a Celsius value: ";
	cin >> celsius;
	fahrenheit = change(celsius);
	cout << celsius << " degrees Celsius is " << fahrenheit <<" degrees Fahrenheit." << endl;
	return 0;
}

float change(float celsius)
{
	float fahrenheit;
	fahrenheit = 1.8 * celsius + 32.0;
	return fahrenheit;
}

6.编写一个程序,其main()调用一个用户定义的函数(以光年值为参数并返回对应天文单位的值)

与第五题类似,但由于数据较大,需使用double型变量存储。

#include<iostream>

double change(double years);

int main()
{
	using namespace std;
	double years,units;
	cout << "Enter the number of light years: ";
	cin >> years;
	units = change(years);
	cout << years << " light years =  " << units <<" astronomical units." << endl;
	return 0;
}

double change(double years)
{
	double units;
	units = 63240 * years;
	return units;
}

7.编写一个程序,要求用户输入小时和分钟数。在main()函数中,将这两个值传递给一个void函数,后者以下面这样的格式显示这两个值。

#include<iostream>

using namespace std;

void print(int hour,int minute);

int main()
{
	int hour,minute;
	cout << "Enter the number of hours: ";
	cin >> hour;
	cout << "Enter the number of minutes: ";
	cin >> minute;
	print(hour,minute);
	return 0;
}

void print(int hour,int minute)
{
	cout <<"Time: " << hour << ":" << minute << endl;
}
发布了17 篇原创文章 · 获赞 10 · 访问量 422

猜你喜欢

转载自blog.csdn.net/acslsr/article/details/103996618