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: "