第七章编程练习

本文提供了一系列C++编程练习,涵盖了动态规划、算法和数据结构的应用。练习包括计算调和平均数、处理高尔夫成绩、操作box结构、计算彩票中奖概率、实现阶乘函数、数组操作及指针使用等,旨在提升编程技能和问题解决能力。
摘要由CSDN通过智能技术生成

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

double harmean(double x, double y);

int main(void)
{
   
	double n1, n2, result;

	cout << "Please enter two numbers, until one of them is zero:";
	cin >> n1 >> n2;

	while ((n1 != 0) && (n2 != 0))
	{
   
		result = harmean(n1, n2);
		cout << "The harmean is " << result << endl;
		cout << "Please enter two numbers, until one of them is zero:";
		cin >> n1 >> n2;
	}
	
	return 0;
}

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

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

const int MAX = 10;
int FillScores(double arr[], int n);
void ShowGolfScores(double arr[], int n);
double AverageGolf(double arr[], int n);

int main(void)
{
   
	double golf[MAX], average;
	 
	int size = FillScores(golf, MAX);

	if (size > 0)
	{
   
		ShowGolfScores(golf, size);
		average = AverageGolf(golf, size);
		cout << "The average of scores is " << average << endl;
	}
	else
	{
   
		cout << "No scores!" << endl;
	}
	return 0;
}

int FillScores(double arr[], int n)
{
   
	double temp;
	int i;
	for (i = 0; i < MAX; i++)
	{
   
		cout << "Enter golf score, No." << i + 1 << ":";
		cin >> temp;
		if (!cin)
		{
   
			cin.clear();
			while ( cin.get() != '\n');
			cout << "Invalid input, terminate." << endl;
			break;
		}
		else if(temp < 0)
		{
   
			break;
		}
		else
		{
   
			arr[i] = temp;
		}
	}
	return i;
}
void ShowGolfScores(double arr[], int n)
{
   
	cout << "The scores are: ";
	for (int i = 0; i < n; i++)
	{
   
		cout << arr[i] << " ";
	}
	cout << endl;
}
double AverageGolf(double arr[], int n)
{
   
	double average;
	double sum = 0;
	for (int i = 0; i < n; i++)
	{
   
		sum += arr[i];
	}
	average = sum / n;
	return average;
}

3.下面是一个结构声明:
struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};
a.编写一个函数,按值传递box结构,并显示每个成员的值。
b.编写一个函数,传递box结构的地址,并将volume成员设置为其他三维长度的乘积。
c.编写一个使用这两个函数的简单程序。

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

void SetBoxVolume(Box *p);
void ShowBox(Box box);

int main(void)
{
   
	Box box = {
   "cube", 3, 4, 5};

	SetBoxVolume(&box);
	ShowBox
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值