I am writing a program where I calculate the area of a circle, the volume of a sphere, and the surface area of a sphere and I need a way to get one source of user input. I don’t want the program to keep asking for user input the way that it is in the functions.
I want my program to run like this:
Enter a radius in inches: 3.3 Area of a circle is 34.21 square inches Volume of a sphere is 150.53 cubic inches Surface area of a sphere is 136.85 square inches
This is what I have so far though:
#include <iostream>
#include <cmath>
#define Pi 3.1415
using namespace std;
void area_of_circle() {
double radius;
std::cout << "Enter a radius in inches: " << endl;
cin >> radius;
double areaCircle = Pi * radius * radius;
std::cout << "The area of the circle is " << std::ceil(areaCircle * 100.0) / 100.0 << " square inches";
}
void volume_of_sphere() {
double radius;
std::cout << "Enter a radius in inches: " << endl;
cin >> radius;
double volumeSphere = (4/3) * Pi * radius * radius * radius;
std::cout << "The volume of the sphere is " << std::ceil(volumeSphere * 100.0) / 100.0 << " cubic inches";
}
void surface_area_of_sphere() {
double radius;
std::cout << "Enter a radius in inches: " << endl;
cin >> radius;
double surfaceAreaSphere = 4 * Pi * radius * radius;
std::cout << "The volume of the sphere is " << std::ceil(surfaceAreaSphere * 100.0) / 100.0 << " square inches";
}
int main() {
area_of_circle();
volume_of_sphere();
surface_area_of_sphere();
}
Why not create a separate function do get the input and have it return it to a global variable in main? Then, you could simply pass the value as an argument to each of the other functions you are calling and not ask for the radius in any of those. Instead, you would just output the other sentences with the calculations.
Also, your other functions other than input do not need to request the radius input again. Also, make sure the input function does return the radius gathered from the user entering it.
Looks good now. The only thing I think you would want to change is to remove the << endl after the "Enter a radius in inches: ", so that the user enters the value on the same line.