Place
your mouse in the areas below to see comments about the corresponding sections
of code |
|
Code
|
|
|
/* An example on the use of functions : function with multiple returns file: 5ex3.cpp FALL 1998 ___________________________________ Jacob Y. Kazakia jyk0 October 5, 1998 Example 3 of week 5 Recitation Instructor: J.Y.Kazakia Recitation Section 01 ___________________________________ Purpose: This program uses a function named properties
to calculate the volume and total surface of a right prizm
which has as base a n-sided regular polygon inscribed in
a circle of a given radius. The function properties has the following parameters: a) The radius of the base ( in meters ) b) The height ( in meters ) c) An integer m denoting the number of sides of the
regular polygon d) The volume e) The area denoting the total surface area of the solid. The first 3 arguments are inputs, the last two are ouputs. Algorithm: The length of each side of the regular polygon
is calculated by: side = 2 * r * sin( pi / m ) Why? The area of the base is calculated by : base_area = pi * r * r * { sin(2*pi/m) / (2*pi/m) } why? The volume is: volume = base_area * height The total surface area is: area = 2 * base_area + m * side * height */
|
|
|
#include <iostream.h> #include <math.h> // Prototype the function void properties(float radius, float height, int m, float& volume, float& area);
|
|
|
|
// Define the constant pi const float PI = 3.14159265358979 ; void main() { // declare the variables of the main function int m ; // integer denoting the number of sides float r ; // the radius float h ; // the height of the object float volume, area ; // "hard code" the input variables r = 2.34 ; // meters h = 1.12 ; // meters m = 9 ;
|
|
|
// calculate volume and area ( the output variables)
by invoking the function properties( r, h, m, volume, area );
|
|
|
// output the variables cout<<"\n\n For the given geometry: radius = "<< r <<"
height = "<< h; cout<<" both in meters" << endl; cout<<" and for a "<< m <<"-sided solid we have volume = "; cout << volume << " cubic meters" << endl; cout<<" and total surface area = "; cout << area << " square meters" << endl; // hold the screen cout<<" \n\n enter e (exit) to terminate the program...."; char hold; cin>>hold; }
|
|
|
// definition of function volume void properties(float radius, float height, int m, float& volume, float& area) { // declare the local variables float pi = 3.141592654; float side, base_area; side = 2 * radius * sin(pi/m); base_area = pi * radius * radius * (sin(2*pi/m)/(2*pi/m)); area = 2 * base_area + m * side * height; volume = base_area * height; // no returns here }
|
|
|
/* HERE IS THE OUTPUT For the given geometry: radius = 2.34 height = 1.12 both in meters and for a 9-sided solid we have volume = 17.739 cubic meters and total surface area = 47.8114 square meters enter e (exit) to terminate the program.... */
|
© 2001 J.Y. Kazakia. All rights reserved