I have to create a sphere class with the following attributes:
Write a class Sphere with the following properties:
Private attributes: (1) X, Y, Z coordinates of the center (2)
Radius
Accessor and mutator methods to
• Set and get the X, Y, and Z
coordinates
• Set and get the radius
• Get the volume and surface
area if a sphere.
For a sphere,
Volume = 4πr3/3
Surface Area = 4πr2
Write a main
program to test the sphere class.
I have never worked with classes before. I think I did this correctly. However, my output for my Volume and my Surface Area comes out really strange. Below is my program and my output.
PROGRAM
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
using namespace std;
class Sphere {
private:
float X;
float Y;
float Z;
float R;
float Volume;
float SurfaceArea;
public:
float DefineCoordinates(float x, float y, float z);
void DefineRadius(float radius);
double GetVolume()
{
return (((4 * M_PI*pow(R, 3))) / 3);
}
double GetSurfaceArea()
{
return (4 * M_PI*pow(R, 2));
}
float GetX();
float GetY();
float GetZ();
};
float Sphere::GetX() {
return X;
}
float Sphere::GetY() {
return Y;
}
float Sphere::GetZ() {
return Z;
}
float Sphere::DefineCoordinates(float x, float y, float z) {
X = x;
Y = y;
Z = z;
return 0;
}
void Sphere::DefineRadius(float radius) {
R = radius;
}
int main() {
float inputr, radius, x, y, z;
Sphere sphere;
double Volume = sphere.GetVolume();
double SurfaceArea = sphere.GetSurfaceArea();
char open = '(';
char close = ')';
char comma = ',';
cout << "Please input the center of the sphere in the fashion (X,Y,Z) and press enter: ";
cin >> open >> x >> comma >> y >> comma >> z >> close;
cout << "Please define the radius of the sphere: ";
cin >> inputr;
sphere.DefineCoordinates(x, y, z);
sphere.DefineRadius(inputr);
cout << "This sphere has a center of (" << sphere.GetX() << ", " << sphere.GetY() << ", " << sphere.GetZ() << ")." << endl;
cout << "This sphere has a radius of " << inputr << "." << endl;
cout << "This computes to a volume of " << Volume << " units cubed, and a surface area of " << SurfaceArea << "." << endl;
}
OUTPUT
No matter what I input as radius, I will get:
This computes to a volume of -5.18547e+24 units cubed, and a surface
area of 1.4488e+17.
What am I doing wrong?? Also, any other advice to clean up my class would be helpful!
You call the GetVolume() method too early. Call it after actually taking the radius from the user.
int main() {
float inputr, radius, x, y, z;
Sphere sphere;
double SurfaceArea = sphere.GetSurfaceArea();
char open = '(';
char close = ')';
char comma = ',';
cout << "Please input the center of the sphere in the fashion (X,Y,Z) and press enter: ";
cin >> open >> x >> comma >> y >> comma >> z >> close;
cout << "Please define the radius of the sphere: ";
cin >> inputr;
sphere.DefineCoordinates(x, y, z);
sphere.DefineRadius(inputr);
double Volume = sphere.GetVolume();
cout << "This sphere has a center of (" << sphere.GetX() << ", " << sphere.GetY() << ", " << sphere.GetZ() << ")." << endl;
cout << "This sphere has a radius of " << inputr << "." << endl;
cout << "This computes to a volume of " << Volume << " units cubed, and a surface area of " << SurfaceArea << "." << endl;
}
Like the above.
Simple,
You read the volume and the surface before defining the radius.
Your problem is, that you are calling the GetVolume() and GetSurfaceArea() functions before you are reading the input. Your calculations are based on uninitialized values.
You should move the functions calls after the calls of DefineCoordinates()and DefineRadius()
Your main should look similar to this:
int main() {
float inputr, radius, x, y, z;
Sphere sphere;
char open = '(';
char close = ')';
char comma = ',';
cout << "Please input the center of the sphere in the fashion (X,Y,Z) and press enter: ";
cin >> open >> x >> comma >> y >> comma >> z >> close;
cout << "Please define the radius of the sphere: ";
cin >> inputr;
sphere.DefineCoordinates(x, y, z);
sphere.DefineRadius(inputr);
double Volume = sphere.GetVolume();
double SurfaceArea = sphere.GetSurfaceArea();
cout << "This sphere has a center of (" << sphere.GetX() << ", " << sphere.GetY() << ", " << sphere.GetZ() << ")." << endl;
cout << "This sphere has a radius of " << inputr << "." << endl;
cout << "This computes to a volume of " << Volume << " units cubed, and a surface area of " << SurfaceArea << "." << endl;
}
Sphere has a default constructor, which does not initialize the X, Y and Z members. Directly after construction, you try to calculate the volume and surface from these indefinite values.
In other words,
double Volume = sphere.GetVolume();
does not define a mathematical relation (it seems you think it does), it's an imperative. The volume will be calculated once (used for initialization of Volume) and its value will not change with you changing sphere's attributes. Do this calculation after you've called Sphere::DefineCoordinates and Sphere::DefineRadius.
Or, make it impossible to construct such an invalid Sphere object. Learn how to use constructors, and use some const qualifiers from time to time.
For completeness, what are Sphere::Volume and Spehre::SurfaceArea for? Why does Sphere::DefineCoordinates return a float (always 0) and why is my answer not at the top?
Related
I am a newbie in C++ and I am quite confused in programmer - defined functions.
It shows these errors
40 [Error] cannot convert 'double' to 'double(double, double)' in assignment
40 [Error] assignment of function 'double total_area(double, double)'
I cannot enter total_area = cross_area + side_area;
If I try to remove the double, it results to more errors
I can't find any information in youtube or in google that seems helpful.
// P33_2.cpp This program illustrates the local and global variables and call-by-value.
// This program computes the side area and the cross section area of a cylinder
#include<iostream>
#include<cmath>
using namespace std;
const double PI = 3.14159; // This variable is defined globally, known to all functions in this program as PI
double cross_area(double r); // Function prototype for function cross_area
double side_area(double r, double h); // Function prototype for function Side_area
double total_area(double cross_area, double side_area);
int main(void)
{
double h, r; //variables local to the main function
cout << "Enter the radius and the height of the cylinder in Cm <Enter> ";
cin >> r >> h;
cout << endl;
cout << "Before I do any computation or call any function, I want to let you know that \n";
cout << "you have entered r = " << r << " and h = " << h << "." << endl;
cout << "I am planning to use inch, thus in the first function, I will convert r, and " << endl;
cout << "in the second one I will convert h \n";
cout << "The cross section area of the cylinder is " << cross_area(r) << " inch-sqr endl\n";
cout << "The side area of the cylinder is " << side_area(r,h) << " inch-sqr \n\n";
cout << "The total surface area is "<< total_area << "inch-sqr \n \n";
return 0;
}
double cross_area(double r)
{
//Cross secion area includes the disks at the bottom and the top
r = r * 0.3937; // converting r to inch
return 2*PI*pow(r,2);
}
double side_area(double r, double h)
{
double area; //variable local to Side_area function
h = h * 0.3937; // converting h to inch
area = 2*PI*r*h;
return area;
}
double total_area(double cross_area, double side_area)`enter code here`
{
total_area = cross_area + side_area;
return 0;
}
See improved working code below
in your code, you have not passed any argument to total_area function. How do you think you will calculate area without passing arguments.
cout << "The total surface area is "<< total_area << "inch-sqr \n \n";
#include<iostream>
#include<cmath>
using namespace std;
const double PI = 3.14159; // This variable is defined globally, known to all functions in this program as PI
double cross_area(double r); // Function prototype for function cross_area
double side_area(double r, double h); // Function prototype for function Side_area
double total_area(double cross_area, double side_area);
int main(void)
{
double h, r; //variables local to the main function
cout << "Enter the radius and the height of the cylinder in Cm <Enter> ";
cin >> r >> h;
cout << endl;
cout << "Before I do any computation or call any function, I want to let you know that \n";
cout << "you have entered r = " << r << " and h = " << h << "." << endl;
double dcross_area = cross_area(r);
double dside_area= side_area(r,h);
cout << "I am planning to use inch, thus in the first function, I will convert r, and " << endl;
cout << "in the second one I will convert h \n";
cout << "The cross section area of the cylinder is " << cross_area(r) << " inch-sqr endl\n";
cout << "The side area of the cylinder is " << side_area(r,h) << " inch-sqr \n\n";
cout << "The total surface area is "<< total_area(dcross_area, dside_area) << "inch-sqr \n \n";
return 0;
}
double cross_area(double r)
{
//Cross secion area includes the disks at the bottom and the top
r = r * 0.3937; // converting r to inch
return 2*PI*pow(r,2);
}
double side_area(double r, double h)
{
double area; //variable local to Side_area function
h = h * 0.3937; // converting h to inch
area = 2*PI*r*h;
return area;
}
double total_area(double cross_area, double side_area)
{
return cross_area + side_area;
}
Here I have my code to calculate the distance between the user inputted points, and the calculateDistance function should take in two pointers, I feel like I had it setup right, but when I run the code I get this error: bash: line 12: 25372 Segmentation fault $file.o $args
Code:
struct Point{
float x;
float y;
};
float calculateDistance(struct Point *p1, struct Point *p2){
float *fx, *fy;
*fx = (*p1).x - (*p2).x;
*fy = (*p1).y - (*p2).y;
return sqrt((*fx * *fx) + (*fy * *fy));
}
int main()
{
struct Point *p1, *p2, q, w;
p1 = &q;
p2 = &w;
//float distance;
cout << "Enter coordinate for p1x: " << endl;
cin >> (*p1).x;
cout << "Enter coordinate for p1y: " << endl;
cin >> (*p1).y;
cout << "Enter coordinate for p2x: " << endl;
cin >> (*p2).x;
cout << "Enter coordinate for p2y: " << endl;
cin >> (*p2).y;
//distance = calculateDistance(*p1, *p2);
cout << "Distance between points: " << calculateDistance(p1, p2) << endl;
return 0;
}
One fault is in function calculateDistance. Please change it as
float calculateDistance(struct Point *p1, struct Point *p2){
float fx, fy;
fx = (*p1).x - (*p2).x;
fy = (*p1).y - (*p2).y;
return sqrt((fx * fx) + (fy * fy));
}
Hello I have class point and the job is to make array of points (objects of the same class), but the class has more than one constructor. How to declare which one of them I want in my array? The code:
class point
{
private:
double pointX, pointY;
string color;
int form;
public:
point();
point(double, double, string color = "red", int form = 2);
point(string color = "red", int form = 2);
~point() {
cout << "Deleting object point" << endl;
}
inline void print();
inline void distance();
};
point::point(double x, double y, string color = "red", int form = 2) {
cout << "enter x coordinate of the point x = "; cin >> pointX;
cout << "enter y coordinate of the point y = "; cin >> pointY;
}
point::point(string color = "red", int form = 2) {
cout << "enter x coordinate of the point x = "; cin >> pointX;
cout << "enter y coordinate of the point y = "; cin >> pointY;
}
point::point() {
cout << "enter x coordinate of the point x = "; cin >> pointX;
cout << "enter y coordinate of the point y = "; cin >> pointY;
cout << "enter color of the point "; getline(cin, color);
cout << "enter number form 1 - 3 for the form of the point "; cin >> form;
}
inline void point::print() {
cout << "the x coordinate of the point is x = " << pointX << endl;
cout << "the y coordiante of the point is y = " << pointY << endl;
cout << "the color of the point is " << color << endl;
if (form = 1) cout << "the form is circle" << endl;
if (form = 2) cout << "the form is square" << endl;
if (form = 2) cout << "the form is cross" << endl;
}
inline void point::distance() {
double z;
z = sqrt(pointX*pointX + pointY*pointY);
cout << "distance between the point and the start of coordinate system is " << z << endl;
}
double pointDistatnce() {
double z, x, y;
point points = new point[4];
}
!!! point points = new point[4];` // here must be the array of objects but it shows me error that "class point has more than one default constructor"?
And I want to use the constructor without parameters so for the user to construct his own point. Here are the errors from the error list;
!! no suitable constructor exists to convert from "point
!! class "point" has more than one default constructor
point(); declares a default constructor. So does point(string color = "red", int form = 2); Either get rid of the first one and just use the second, or get rid of the default value for color in the second.
Edit based on the extra info you posted: You are looking for the compiler to read the programmer's mind. You defined a constructor with no parameters that does one thing, but you defined a constructor with two optional parameters that does a different thing. When the constructor is invoked and given no parameters, does that mean it should execute with no parameters or does it mean it should execute with the default values for the two optional parameters.
None of that changes my original answer. It just means you need to think a bit in order to use that answer. In the partial code you initially provided, one might hope that the two constructors that each could be invoked with no parameters were redundant with each other, so just dropping the redundancy would fix it. But since you want the programmer to be able to invoke one of two different constructors, you need to think of a way to tell the compiler which one should be used.
While rethinking your design, you should also try to drop the idea of using cin within a constructor. It is not technically wrong. But it is a bad enough idea that you shouldn't do it.
I'm making a program in my programming class for homework involving inheritance that calculates a distance between one, two and three dimensions. Basically If the User chooses to calculate in one dimension, It should make a calculation (x) on a number line. If the user chooses two dimensions, The user enters a pair of (x,y) coordinates like a XY Cartesian coordinate plane, to which the distance is calculated between the two points. If the user chooses a 3 dimension calculation, the user should enter a pair of x,y,and z coordinates to which it also should calculate the distance between the two. However the problem that I am currently having is that I am getting a total of 18 various types of errors in my function definitions mostly coming from stating that the function call does not match the argument list. Is there a way to explain these simply and give me an idea on how to solve my error(s)? Here is my code, first staring with my one dimension definition, then the two dimension definition, the three dimension definition and finally my main. The lines with errors have been Added properly. Thanks.
//definition of 1st dimension
#include <iostream>
#include "OneDimenson.h"
OneDimension::OneDimension(int x)
{ //sets x
x = x;
}
int OneDimension::GetX()
{ // returns x
return x;
}
int OneDimension::CalcDistance(OneDimension point2)
{ //calculates the distance between the instance(object created) and the 1d point
int distance = 0;
distance = point2.GetX - x; //2 ERRORS HERE: 1.) Function doesent match
// argument list and 2.) illegal, left operand has type int.
cout << "Distance Calculated." << endl;
return distance;
}
// definition of 2nd definiton
#include <iostream>
#include "OneDimenson.h"
#include "TwoDimension.h"
TwoDimension::TwoDimension(int x, int y):OneDimension(x)
{ // sets x and y
x = x;
y = y;
}
int TwoDimension::GetY()
{ // returns y
return y;
}
int TwoDimension::CalcDistance(OneDimension point2)
{ // calculates the distance between the 2nd distance and the 1d point.
int distance = 0;
distance = point2.GetX - x; // 2 ERRORS: 1.) function call missing from
// arguement. 2.) illegal, left operand has a type of int.
return distance;
}
int TwoDimension::CalcDistance(TwoDimension point2)
{ // calculates the distance between the instance and the 2nd point.
int distance = 0;
distance = point2.GetY - x; //ERROR HERE
return distance;
}
// definition of the 3d dimension
#include "OneDimenson.h"
#include "TwoDimension.h"
#include "ThreeDimension.h"
ThreeDimension::ThreeDimension(int x, int y, int z):TwoDimension(x,y)
{ //sets x, y, and z
cout << "please set the dimension for x." << endl;
cin >> x;
cout << "please set the dimension for y." << endl;
cin >> y;
cout << "please set the dimension for z." << endl;
cin >> z;
}
int ThreeDimension::GetZ()
{ //returns z
return z;
}
int ThreeDimension::CalcDistance(OneDimension point2)
{ // calculates the distance between the 3d instance and the 1d point.
int distance = 0;
distance = point2.GetX - z; //2 Errors: 1.) Function doesent match
// argument list and 2.) illegal operand has type int.
return distance;
}
int ThreeDimension::CalcDistance(TwoDimension point2)
{ // calculates the distance between the 2d instance and the 2d point.
int distance = 0;
distance = point2.GetY - y; //2 ERRORS: 1) Function call missing from
// arguement. 2) illegal, left operand has a type of int.
return distance;
}
int ThreeDimension::CalcDistance(ThreeDimension point2)
{ // calculates the distance between the instance and the 3d point.
int distance = 0;
distance = point2.GetZ - x; //2 ERRORS: 1) Function call missing from
// arguement and 2) illegal, left operand has type of int
return distance;
}
// This is the main
#include <iostream>
#include <string>
#include "OneDimenson.h"
#include "TwoDimension.h"
#include "ThreeDimension.h"
using namespace std;
int main()
{
int UserChoice = 0;
int x = 0;
int y = 0;
int z = 0;
int point2 = 0;
do
{
cout << "-----CONSOLE MENU----" << endl;
cout << "Would you like to calculate 1d, 2d or 3d?" << endl;
cout << "(PRESSING 0 ENDS PROGRAM)." << endl;
cout << "1.) 1d calculation" << endl;
cout << "2.) 2d calculation" << endl;
cout << "3.) 3d calculation" << endl;
cin >> UserChoice;
switch (UserChoice)
{
case 0:
break;
case 1:
// if user selects 1, then the user selects x, then point 2, to which the distance is calculated.
cout << "1d calculation chosen. Enter the x point: " << endl;
cin >> x;
OneDimension OneDimension(x);
cout << "Enter the instance Point: " << endl;
cin >> point2;
cout << "The distance between the two points (in 1d space) is: " << OneDimension.CalcDistance(point2);
cout << " " << endl;
case 2: // ERROR: ONE DIMENSION IS SKIPPED BY CASE LABEL
// if user selects 2, the user then selects the x and y coordinate. then the distance is calculated.
cout << "2d calculation chosen. Enter the x part of the point: " << endl;
cin >> x;
cout << "Enter the y part of the point." << endl;
cin >> y;
cout << "Enter the instance point." << endl;
cin >> point2;
TwoDimension TwoDimension(x,y);
cout << "The distance between the two points (in 2d space) is: " << TwoDimension.CalcDistance(point2);
cout << " " << endl;
case 3: //ERROR: TWO DIMESION AND ONE DIMENSION ARE SKIPPED BY CASE LABEL:
// if user selects 3, then the user selects x, y and z coordinate. Then the distance is calculated.
cout << "3d calculation chosen. Enter the x part of the point: " << endl;
cin >> x;
cout << "Enter the y part of the point." << endl;
cin >> y;
cout << "Enter the z part of the point." << endl;
cin >> z;
cout << "Enter the instance point." << endl;
cin >> point2;
ThreeDimension ThreeDimension(x, y, z);
cout << "The distance between the two points (in 3d space) is: " << ThreeDimension.CalcDistance(point2);
cout << " " << endl;
default: //ERROR ABOUT HOW ONEDIMENSION, TWODIMENSION, AND THREEDIMENSION ARE SKIPPED BY DEFAULT LABEL
break;
}
} while (UserChoice != 0);
return 0;
}
When you call
OneDimension.CalcDistance(point2);
You are passing it point2 which is of type int. However, at the place you define the function
OneDimension::CalcDistance(OneDimension point)
You specify that the function parameter should be of type OneDimension. Since the types do not match, this generates the errors. You have the same problem with TwoDimension and ThreeDimension.
I need help with fixing the program. It is not running. I keep getting the warning control reaches end of non void function. I dont know how to fix it. Please help me. The program is suppose to find the volume or the surface area of a sphere. I get the warning on the last 2 }
#include <iostream>
#include <iomanip>
#include <cmath>
#include <math.h>
using namespace std;
char s = '\0';
const char SENTINEL = 's';
float radius, answer;
void get_radius (float&);
float surface_area (float);
float volume (float);
float cross_section (float);
const float PI = 3.14;
int main()
{
cout << "This program will let you input the radius of a sphere to find its volume or surface area." << endl << endl;
cout << "Enter 'v' for volume or 'a' for surface area of a sphere" << endl;
cout << "'s' to stop" << endl;
cin >> s;
while (s != SENTINEL)
{
get_radius (radius);
if(s == 'V')
{
volume (radius);
}
else if(s == 'A')
{
surface_area (radius);
}
cout << "Enter 'v' for volume or 'a' for surface area of a sphere" << endl;
cout << "'s' to stop" << endl;
cin >> s;
}
system("PAUSE");
return 0;
}
void get_radius (float& radius)
{
cout << "Please enter the radius of the sphere: " << endl;
cin >> radius;
}
float volume (float radius){
float answer;
answer = 4.0/3.0 * PI * pow (radius, 3);
cout << "The volume is: " << answer << endl;
}
float surface_area (float radius){
float answer;
answer = 4.0 * PI * pow(radius, 2);
cout << "The surface area is: " << answer << endl;
}
your function declaration must match what you are returning. You have to make sure you are returning values from functions that are declared that they are returning something.
volume() and surface_area() are printing things with cout but are not returning anything.
float volume (float radius){
float answer;
answer = 4.0/3.0 * PI * pow (radius, 3);
cout << "The volume is: " << answer << endl;
return answer;
}
float surface_area (float radius){
float answer;
answer = 4.0 * PI * pow(radius, 2);
cout << "The surface area is: " << answer << endl;
return answer;
}
When you declare the type of a function, you need to return a value of that type. For example, your function:
float volume (float radius) {}
Needs a return statement returns a value of type float.
If you don't need the function to actually return something, then declare it void to let the compiler know that. In this case:
void volume (float radius)
Just be careful, since void functions must NOT return a value (they can use a bare return statement, though).
Note also that potential paths which skips the return statement can trigger this error. For example, I could have this function:
int veryBadFunction(int flag)
{
if (flag == 1) {
return 1;
}
}
In this case, even though there IS a return statement in the function, it gets skipped any time the value of flag is something other than '1'. This is why the error message is worded control reaches...