I'm working on below program and I want the program to do the same thing, but with not one main() function, but instead one main() function PLUS one user defined function called computeConeVolume that contains the calculation. In other words I want to remove the one line calculation and replace it with a function call, then write and add the function below main with the calculation, surrounded any other syntax that I need to complete it.
The function should contain local variables and a constant declared and must have the calculation, it may not do anything else such as input or output. Should be able to declare "global" variables anywhere but no variables above or outside of main() and the function are allowed. A value-returning function should be used because it's a little simpler to understand, but you can employ a void function. Need to have a function prototype at the top of the code, then main, then your function.
Need some help with this since I'm new to C++ and trying to learn.
//Cone Volume Calculator Program
#include <iostream>
using namespace std;
int main( )
{
//Declare variables and constants
double coneRadius = 0.0;
double coneHeight = 0.0;
const double PI = 3.1415;
double coneVolume = 0.0;
//Prompt the user for inputs
cout << "Enter the radius of the cone: ";
cin >> coneRadius;
cout << "Enter the height of the cone: ";
cin >> coneHeight;
//Do the calculation
coneVolume = 0.3333 * PI * coneRadius * coneRadius * coneHeight;
//Display the result
cout << "The volume of your cone is: " << coneVolume << endl;
Do you know how functions work? If so, its pretty easy. In case you forget, remember that int main() is a function.
So, for your case:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
// declare a function prototype (you specified that the function will go below
// main, but first we need to say that it exists):
double computeConeVolume(double radius, double height);
int main() {
// ...
coneVolume = computeConeVolume(coneRadius, coneHeight); // call the function
// ...
}
// Now we give it the implementation for the function:
double computeConeVolume(double radius, double height) {
constdouble pi = 3.141592654;
return (1.0 / 3.0) * pi * radius * radius * height;
}
For more details on how functions work, just look it up on a C++ tutorial (for example, the one on this site).
Thanks NT3 for the solution.
However, I cannot use a 1 anywhere since that number is so simple and can give the right answer sometimes if the program is wrong. So I need to eliminate the 1.