What is going on here?

I was set a challenge, and I thought that I had done well, but it appears not.
The challenge was this:
"Write a program that repeatedly asks the user to input a pair of numbers until at least one of the pair is 0.
The function should return the answer to main(), which should report the result.
(The harmonic mean = 2.0 * x * y / (x + y))"



The problem with my simple code is that nothing returns from the function. and when the user types a 0, an infinite loop occurs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include "stdafx.h"
#include <iostream>
#include <cctype>
using std::cout;
using std::cin;

double harmonicmean(unsigned int x, unsigned int y);

int main()
{
	unsigned int x,y;
	cout << "Please enter two positive integers\n";

	cin >> x >> y;

	while(x!= 0 || y!= 0)
	{
		if(isalpha(x) || isalpha(y))
			break;

		harmonicmean(x,y);
		cout << "Enter another two numbers, or zero to stop\n";
		cin.clear();
		cin >> x >> y;
	
	}



	char faefasdfsdg;
	cin >> faefasdfsdg;
	return 0;
}

double harmonicmean(unsigned int x, unsigned int y)
{
	double total = (2.0 * x * y) / (x + y);
	
	return total;
}


Can anyone give me any hints as to what I've done wrong?
Last edited on
The function does return the value. The problem is that you're not doing anything with it.

Try

1
2
double returnedValue = harmonicmean(x,y);
cout << returnedValue;


As for stopping, look at this:

while(x!= 0 || y!= 0)

Let's say that I enter x as zero, and y as some other number. Will the loop stop? No. The loop will keep going as long as x isn't zero OR y isn't zero. The only way to stop the loop is to make both x and y zero.

Try

while(x!= 0 && y!= 0)

Now, the loop will keep going if x isn't zero AND if y isn't zero. Making x zero, or making y zero, will break the loop.
Last edited on
Thank you so much!

Yeah, the loop did sound a bit weird in my head too. (It didn't make any sense in English.)

The returnedValue worked!

You're the best!
Topic archived. No new replies allowed.