Heavy-handed code needs optimization

My program, as it currently sits below, accomplishes everything that the problem asks of me:
(Write a program that has a function that prompts for three values. The function will then return the average of those values to main. The returned value will then be displayed to the screen).

Also, I wanted to make the program so that you could keep entering new values, which I did.
However, I know that my code is very explicit, and I am programming "with a hammer". My main function is crowded because I have repeated a block of code in order to get the program to be repeatable.

Can someone please lead me in the right direction with regard to making my code more efficient?

Thanks in advance.

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
41
42
43
44
45
 #include <iostream>
using namespace std;

double mean(double x, double y, double z);

int main()
{
	double first, second, third;
	char choice;

	cout << " Please enter three different values: " << endl;
	cin >> first >> second >> third;

	cout << " The average of your three numbers is; \t" << mean(first, second, third) << endl;	
	
	cout << "\n Would you like to play again? " << endl;
	cin >> choice;
	cout << endl;

	while (choice == 'y' || choice == 'Y')
	{
		cout << "\n Please enter three different values: " << endl;
		cin >> first >> second >> third;

		mean(first, second, third);

		cout << " The average of your three numbers is; \t" << mean(first, second, third) << endl;	

		cout << "\n Would you like to play again? " << endl;
		cin >> choice;
		cout << endl;

	}
	
	return 0;

}

double mean(double x, double y, double z)
{
	
	double average = (x + y + z) / 3.0;

	return average;
}
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
#include <iostream>

double mean( double x, double y, double z ) { return (x+y+z) / 3.0 ; }

bool again()
{
	std::cout << "\n Would you like to play again (y/n)? " ;
	char choice ;
	std::cin >> choice;

	if( choice == 'y' || choice == 'Y' ) return true ;
	else if( choice == 'n' || choice == 'N' ) return false ;
	else return again() ;
}

int main()
{
    do
    {
        double first, second, third;
        std::cout << " Please enter three different values: " << '\n' ;
        std::cin >> first >> second >> third;

        std::cout << " The average of your three numbers is; \t" << mean(first, second, third) << '\n' ;
    }
    while( again() ) ;
}
Thank you, I will attempt to understand all of it. Thanks again.
Topic archived. No new replies allowed.