Bootstrap

C++ Primer Plus(第六版)中文版编程练习答案

48 C++ Primer Plus(第六版)第七章 编程练习答案

1

#include<iostream>
using namespace std;

double tiaohe(double a, double b);

int main()
{
   
	double x, y, ret;
	cout << "Enter x and y (0 to quit):" << endl;
	cin >> x >> y;
	while (x != 0 && y != 0)
	{
   
		ret = tiaohe(x, y);
		cout << "x 和 y 的调和平均数为:" << ret << endl;
		cout << "Enter next x and y (0 to quit):" << endl;
		cin >> x >> y;
	}

	system("pause");
	return 0;
}

double tiaohe(double x, double y)
{
   
	return 2.0 * x * y / (x + y);
}

2

#include<iostream>
using namespace std;

const int Max = 10;

int input_grade(int grade[],int max);
void show_grade(int grade[], int size);
double average_grade(int grade[], int size);

int main()
{
   
	int grade[Max];
	int size = input_grade(grade,Max);
	show_grade(grade, size);
	double ave= average_grade(grade, size);

	system("pause");
	return 0;
}

int input_grade(int grade[],int max)
{
   
	int i = 0;
	cout << "Enter grades(less than 10 and char to quit):" << endl;
	
	//把判断数组是否溢出放在前面,输入判断放在后面
	while (i<max && cin >> grade[i])
	{
   
		++i;
	}
	return i;
}

void show_grade(int grade[], int size)
{
   
	cout << "grades: " << endl;
	for (int i = 0; i < size; i++)
	{
   
		cout << grade[i] << " ";
	}
	cout << endl;
}

double average_grade(int grade[], int size)
{
   
	cout << "average: " << endl;
	double average;
	double sum = 0;
	for (int i = 0; i < size; i++)
	{
   
		sum += grade[i];
	}
	average = sum / size;
	cout << average << endl;
	return average;
}


3

#include<iostream>
using namespace std;

struct box
{
   
	char maker[40];
	float height;
	float width;
	float length;
	float volume;
};

void show_box(box b);
float box_volume(box *b);

int main()
{
   
	box b;
	cout << "Enter maker:";
	cin.getline(b.maker, 40);
	cout << "Enter height:";
	cin >> b.height;
	cout << "Enter width:";
	cin >> b.width;
	cout << "Enter length:";
	cin >> b.length;
	/*cout << "Enter volume:";
	cin >> b.volume;*/

	box_volume(&b);
	show_box(b);

	system("pause");
	return 0;
}

void show_box(box b)
{
   
	cout << "maker:" << b.maker << endl << "height:" << b.height << endl
		<< "width:" << b.width << endl << "length:" << b.length << endl
		<< "volume:" << b.volume << endl;
}

float box_volume(box* b)
{
   
	b->volume = b->height * b->length * 
;