9.) (32) Code a program to read in the radius (r), the height (h), and the slant
ID: 3735351 • Letter: 9
Question
9.) (32) Code a program to read in the radius (r), the height (h), and the slant height(s) of a cone from a file. Calculate the surface area (PIrs + PIr) and volume (1/3PIrh) of the cone. 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 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 set up as a global constant. Use the bottom of this sheet. Start with the include statements.Explanation / Answer
Since you have not mentioned the language of your preference, I am providing the code in C++.
Please find the code below with detailed inline comments.
CODE
=====================
#include <iostream>
#include <iomanip>
#include <fstream>
#define PI 3.14159
using namespace std;
double calculateSurfaceArea(double radius, double height, double slant) {
double area = PI * radius * radius + PI * radius * slant;
return area;
}
double calculateVolume(double radius, double height, double slant) {
double volume = PI * radius * radius * height;
return volume;
}
void display(double radius, double height, double slant, double area, double volume) {
cout << radius << setw(15) << height << setw(15) << slant << setw(15)
<< area << setw(15) << volume << endl;
}
void readData() {
ifstream inFile;
double radius, height, slant, area, volume;
inFile.open("cone_data.txt");
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error
}
while (inFile >> radius >> height >> slant) {
area = calculateSurfaceArea(radius, height, slant);
volume = calculateVolume(radius, height, slant);
// display the result
display(radius, height, slant, area, volume);
}
inFile.close();
}
int main() {
cout << fixed;
cout << setprecision(3);
cout << "Radius" << setw(15) << "Height" << setw(15) << "Slant" << setw(15)
<< "Area" << setw(15) << "Volume" << endl;
readData();
}
cone_data.txt (each line contains radius, height and slant height values separated by space)
=====================
7.0 15.5 20.6
10.0 10.0 10.0
16.5 10.9 20.4
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.