Note: the language is C++ Code a program to read in the radius (r) and the heigh
ID: 3678963 • Letter: N
Question
Note: the language is C++
Code a program to read in the radius (r) and the height (h) of a cylinder from a file. Calculate the surface area (2(pi r^2) + (2 pi r) h) and volume of the cylinder (pi r^2 h). Print the answers to the screen with appropriate column headings. There will be multiple sets of data - choose your own end of file handling (sentinel, count first, physical end of the file). The input, calculations, and output must be done in at least three separate methods (other than main) which will be called by main. Use all local variables, except pi, which may be should up as a global constant. Use the back of this sheet.Explanation / Answer
Code:
#include<iostream>
#include <fstream>
#define PI 3.14 //defing pi as a constant
using namespace std;
void read_input(float *r,float *h) //using pointers for radius and height variable
{
ifstream myfile;
myfile.open ("example.txt");
float radius,height;
int cnt=1;
if (myfile.is_open()) {
while (!myfile.eof()) {
if(cnt==1)
myfile>>radius;
else
myfile>>height;
cnt++;
}
}
*r=radius;
*h=height;
myfile.close();
}
float calculate_surface_area(float radius,float height)
{
float sur_area= 2*(PI*radius*radius + PI*radius*height);
return sur_area;
}
float calculate_volume(float radius,float height)
{
float vol= PI*radius*radius*height;
return vol;
}
void output_sur_area(float sa)
{
cout<<"surface area of cylinder is: "<< sa<<endl;
}
void output_volume(float vol)
{
cout<<"volume of cylinder is: "<< vol<<endl;
}
int main () {
float radius , height;
read_input(&radius,&height);
float sur_area,vol;
sur_area= calculate_surface_area(radius,height);
vol = calculate_volume(radius,height);
output_sur_area(sur_area);
output_volume(vol);
return 0;
}
Content of input file:
3.1
4
Sample input and output:
surface area of cylinder is: 138.223
volume of cylinder is: 120.702
if you have any doubt then please comment below...
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.