7.13.1编写一个程序,不断要求用户输入两个数,直到其中一个为0。对于每两个数,程序将使用一个函数来计算它们的调和平均数,并将结果返回给main(),而后者将报告结果。调和平均数指的是倒数平均值的倒数,计算公式如下:
调和平均数 = 2.0 * x * y / (x + y)
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
double getHarmonic(double x, double y);
int main()
{
cout<<"Enter two numbers: ";
double x, y;
while(cin>>x>>y)
{
if(x == 0 || y == 0) break;
cout<<"The harmonic average is "<<getHarmonic(x, y)<<endl;
cout<<"Next enter: ";
}
return 0;
}
double getHarmonic(double x, double y)
{
return 2.0 * x * y / (x + y);
}
7.13.2编写一个程序,要求用户输入最多10个高尔夫成绩,并将其存储在一个数组中。程序允许用户提早结束输入,并在一行上显示所有成绩,然后报告平均成绩。请使用3个数组处理函数来分别进行输入、显示和计算平均成绩。
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int input(double score[], int MaxSize);
void show(const double score[], int ActSize);
double getAverage(const double score[], int ActSize);
int main()
{
double score[10];
int number = input(score, 10);
show(score, number);
double average = getAverage(score, number);
cout<<"The average score is : "<<average<<endl;
return 0;
}
int input(double score[], int Size)
{
cout<<"Enter the all score of the golf: ";
int i=0;
while(cin>>score[i] && i < Size)
i++;
return i;
}
void show(const double score[], int ActSize)
{
cout<<"The all score is: ";
for(int i=0;i<ActSize;i++)
cout<<score[i]<<"\t";
cout<<endl;
}
double getAverage(const double score[], int ActSize)
{
double average =0, sum =0;
for(int i=0;i<ActSize;i++)
sum += score[i];
return sum / ActSize;
}
7.13.3下面是一个结构声明:
struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};
a.编写一个函数,按值传递box结构,并显示每个成员的值
b.编写一个函数,传递box结构的地址,并将volume成员设置为其他三维长度的积
c.编写一个使用这两个函数的简单程序。
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};
void showData(const box b);
void setData(box *b);
int main()
{
box b = { "yang", 5, 6