In: Computer Science
2. Write a program that defines the named
constant PI, const double
PI = 3.14159;, which stores the value
of p. The program should use PI
and the functions listed in Table 6-1
to accomplish the following:
a. Output the value of Pi Output the
value of Pi.
b. Prompt the user to input the value
of a double variable r, which stores the radius of a sphere. The
program then outputs the following:
i. The value of
4Pir2,
which is the surface area of the sphere.
ii. The value of (4/3)Pir3, which is the volume of the sphere
Following is the C++ code for calculating the surface area and volume of a sphere using the radius. Here we are defining a constant double variable PI with value 3.14159 ( A constant variable means which cannot be modified once they are defined).
------------------------------------------------------------------------------------------------
#include
<iostream>
using namespace std;
int main() {
const double PI=3.14159; // Declare a constant
double variable PI
//Following 3 lines declare 3 variables as double type
double r;
double surf_area;
double vol;
cout<<"----------------------------------------"<<endl;
// Following line prints the value of PI
cout<<"PI=" << PI
<< endl;
cout<<"----------------------------------------"<<endl;
cout<<"Please enter the radius of the
sphere:";
//Following line reads the entered
radius and assigns to the variable r
cin>>r;
surf_area=4*PI*r*r; //Calculating surface area of
the sphere=4PIr^2;
vol=(4*PI*r*r*r)/3;//Calculate
volume of the sphere=4/3PIr^3;
//Following two lines prints the surface area and volume of the
sphere
cout<<"----------------------------------------"<<endl;
cout<<"Surface area of the sphere=" << surf_area
<< endl;
cout<<"Volume of the sphere=" << vol <<
endl;
return 0;
}
The screenshot of the result is given below