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