-
not on right track
I am trying to write a program that repeatedly asks you to enter pairs of numbers until at least one of the pair is zero. For each pair, the program should use a function to calculate the harmonic mean of the numbers the function should report the result. This is the code I have done but I am not sure I am on the right track. I just can't seem to get the right things together.
#include <iostream.h>
const int ArSize = 2;
int fill_array(int ar[], int n);
double hmean(double x, double y);
int main(void)
{
int numbers[ArSize];
cout << "Please enter a pair of numbers\n";
cout << "\t(q to quit)\n\n";
int total = fill_array(int ar[], int n);
hmean(total, numbers);
cin.get();
return 0;
}
int fill_array(int ar[], int n)
{
int numbers;
for (int i = 0; i < n; i++)
{
cout << "Enter pairs #" << (i + 1) << ": ";
while (!(cin >> numbers))
{
if (i==0)
break;
return 0;
}
ar[i] = numbers;
}
return i;
}
double hmean(int ar[], int n)
{ int x,y = 0;
for (int i = 0; i < n; i++)
{
return ar[i] = 2*x*y/(x+y);
}
}
-
>int total = fill_array(int ar[], int n);
should be
int total = fill_array(numbers, ArSize);
A better algorithm would be to read in two integers from the user, check to see if one of them is zero, and then branch off.
Code:
inline double hMean(int x, int y)
{
return (double)2 * x * y / (x+y);
}
int main ( void )
{
int high, low;
double d;
for ( ; ; ) { //forEVER
cout<<"Enter two integers"<<endl;
cin>>high>>low;
if ( high == 0 || low == 0 )
return EXIT_SUCCESS;
d = hMean(high, low);
cout<<"The harmonic mean is "<< d <<endl;
}
return EXIT_SUCCESS;
}
/* Untested code */
Throw an infinite loop around the processing in main for the program to run until the user enters a 0 as one of the integers. :)
-Prelude