Goals of exercise are:

  1. Output the value of PI (3.1419, as per exercise).
  2. Prompt user to enter radius, r, and store it.
  3. Calculate surface area of sphere: 4 * PI * r ^ 2
  4. Calculate volume of sphere: (4/3) * PI * r ^ 3
  5. Output the surface area and volume of the sphere.

I've been trying to figure this out for a good hour now and am lost. I've also done searching on Google, on DuckDuckGo, on this site's search function, etc.

Here is what I have so far (all constructive criticism welcome):

// pg356_p4.cpp : Defines the entry point for the console application.
//

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

void userEntry (double& x, double& y);
const double PI = 3.1419;

int main ()
{
	double surface;
	double volume;

	userEntry (surface, volume);

	cout << "The surface area of the sphere is: " << surface << endl;
	cout << "The volume of the sphere is: " << volume << endl;

	system ("pause");
	return 0;
}

void userEntry (double& x, double& y)
{
	cout << fixed << showpoint;
	cout << setprecision(4);
	cout << "The value of PI is: " << PI << endl;

	double r;
	cout << "Please enter a value for the radius: ";
	cin >> r;
	cout << endl;

	double x = 4.0 * 3.1419 * pow (r, 2); // Error provided says: redefinition of "x" and "y"
	double y = (4.0/3.0) * 3.1419 * pow (r, 3);
}

Any help is appreciated.

Recommended Answers

All 3 Replies

You are redeclaring 'x' and 'y'.They have already been declared in the argument list so in lines 37 and 38 you should just assign to those variables and lose the 'double' specifier.

Caut baia correctly points out the error (I believe) but I would like to point out that
you seem to have missed the use of PI.

You declare a const double PI to be 3.1419 and then don't use it. In the line x=4.0 * 3.1419 * pow (r, 2); why not write x=4*PI*pow(r,2); . That way if you have to change PI to something else e.g. a more accurate representation then it is only changed in one place in the code.

Additionally, I guess you know that r*r is the same as pow(r,2) [and sometimes depending on compiler options, quicker and more accurate]

(all constructive criticism welcome):

OK, here goes.

You have a function called userEntry(). Because of the name all the function should do is input data from the user and return the value(s).
Then, make a function to calculate the surface area and return the value.
Make another function to calculate the volume and return the value.
One last function to output the results.

This is modular programming and far superior to all-in-one programming. It's much easier to understand and debug. It will also alleviate the redefinition problem that has been pointed out.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.