Pointers to Return Two Values From a Function

Hello. I am experimenting with pointers. I would like to pass the circumference and volume variables using pointers instead of reference parameters. I know that I'm supposed to use "*" infront of a variable to make it a pointer to another variable's address but I'm not sure how to apply that to this program. I have a function that needs to return two values.

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 <iomanip>
#include <cmath>
using namespace std;

void calcMetrics(double radius, double volumeSphere, double circumferenceCircle);

	

int main(){
	double radius;
	double volumeSphere;
	double circumferenceCircle;

	

	//Request for user input values
	cout << "Please input a value for the radius (Ex Input (mm) :10 )\n";
	cin >> radius;


	calcMetrics(radius, volumeSphere, circumferenceCircle);

	

	cout << "The circumference of a circle with a radius of " << radius << " mm is " << circumferenceCircle << " mm.\n";
	cout << "The volume of a sphere with a radius of " << radius << " mm is " << volumeSphere << " mm.\n";
	

	return 0;
}

	//calcMetrics Function
	void calcMetrics(double radius, double volumeSphere, double circumferenceCircle)
	{
	
	volumeSphere = (M_PI*(pow(radius,2)));
	circumferenceCircle = (M_PI*(pow(radius,3))*(1.33));

	}
closed account (D80DSL3A)
Using pointers:
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
#include <iomanip>
#include <cmath>
using namespace std;

void calcMetrics(double radius, double * volumeSphere, double * circumferenceCircle);
	

int main(){
	double radius;
	double volumeSphere;
	double circumferenceCircle;	

	//Request for user input values
	cout << "Please input a value for the radius (Ex Input (mm) :10 )\n";
	cin >> radius;


	calcMetrics(radius, &volumeSphere, &circumferenceCircle);// pass address	

	cout << "The circumference of a circle with a radius of " << radius << " mm is " << circumferenceCircle << " mm.\n";
	cout << "The volume of a sphere with a radius of " << radius << " mm is " << volumeSphere << " mm.\n";	

	return 0;
}

	//calcMetrics Function
	void calcMetrics(double radius, double * volumeSphere, double * circumferenceCircle)
	{
	
	*volumeSphere = (M_PI*(pow(radius,2)));// dereference to write vaue
	*circumferenceCircle = (M_PI*(pow(radius,3))*(1.33));

	}
Thank you very much for the reply. I appreciate it.

I figured it out before you replied, however, my output has the results flipped.

For example, it's outputting the value of volumeSphere for the circumference output line and outputting the value of circumeferenceCircle for the volumeSphere line.

closed account (D80DSL3A)
Yes, I see that. You have the assignments reversed in the function.
Topic archived. No new replies allowed.