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

本文提供了多个C++编程练习,包括计算调和平均数、处理高尔夫成绩数组、操作box结构、计算彩票头奖概率、实现阶乘函数以及数组的各种操作。通过这些练习,读者可以深入理解C++中函数的使用和数组操作技巧。
摘要由CSDN通过智能技术生成

1.编写一个程序,不断要求用户输入两个数,直到其中的一个为0。对于每两个数,程序将使用一个函数来计算它们的调和平均数,并将结果返回给main(),而后者将报告结果。调和平均数指的是倒数平均值的倒数,计算公式如下:调和平均数=2.0xy/(x+y)

#include <iostream>

double average(double a, double b);

int main(void)
{
   
	using namespace std;
	double a;
	double b;
	double avr;
	cout << "Please enter two numbers: ";
	cin >> a >> b;
	while (a != 0 && b != 0)
	{
   
		avr = average(a, b);
		cout << "The average is: " << avr << endl;
		cout << "Please enter two numbers: ";
		cin >> a >> b;
	}
	cout << "Done!" << endl;
	return 0;
}

double average(double a, double b)
{
   
	double avr;
	avr = 2.0 * a * b / (a + b);
	return avr;
}

2.编写一个程序,要求用户输入最多10个高尔夫成绩,并将其存储在一个数组中。 程序允许用户提早结束输入,并在一行上显示所有成绩,然后报告平均成绩。请使用3个数组处理函数来分别进行输入、显示和计算平均成绩。

#include <iostream>

int input(double arr[], int n);
void show(double arr[], int n);
double average(double arr[], int n);

using namespace std;
const int Max=10;
	
int main()
{
   
	double aver;
	double arr[Max];
	cout << "Input " << Max << " scores: \n";
	cout << "# 1: ";
	int n = input(arr,Max);
	cout << "The score: ";
	show(arr, n);
	aver = average(arr, n);
	cout << "The average is: " << aver << endl;	
	return 0;
}

int input(double arr[], int n)
{
   
	int i = 0;
	while(cin >> arr[i] && ++i < n)
		cout << "# " << i+1 << ": ";
	return i;	
}

void show(double arr[], int n)
{
   
	for(int i = 0; i < n; i++)
		cout << arr[i] << " ";
	cout << endl;
}

double average(double arr[], int n)
{
   
	double sum = 0.0;
	for(int i = 0; i<n; i++)
		sum += arr[i];
	double avr = sum / n;
	return avr;
}

3.a.编写一个函数,按值传递box结构,并显示每个成员的值。
b.编写一个函数,传递box结构的地址,并将volume成员设置为其他三维长度的乘积。
c.编写一个使用这两个函数的简单程序。

#include <iostream>

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

void volume(box * a);
void show(box a);

int main()
{
   
	box A;
	cout << "The maker: ";
	cin.get(A.maker ,40).get();
	cout << "The height: ";
	cin >> A.height;
	cout << "The width: ";
	cin >> A.width;
	cout << "The length: ";
	cin >> A.length;
	
	volume(&A);
	show(A);
	return 0;
}

void show(box a)
{
   
	cout << "The maker: "  << a.maker<<endl;
	cout << "The height: " << a.height<<endl;
	cout << "The width: "  << a.width<<endl;
	cout << "The lenght: " 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值