Calculations coming out wrong
Nov 4, 2012 at 4:45am UTC
I am implementing functions from a header file I have been given, and I can't figure out why the numbers are not what they need to be.
this is part of the .h file I have been given and am using:
1 2 3 4 5 6 7 8 9 10 11
public :
float getDimension();
float getArea();
void setDimension(float newDim);
void setArea(float newArea);
Square(); //set initial dimension to 1.0
Square(float initialDim);
private :
float dimension;
};
This is the code I am writing :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
float Square::getDimension(){
return dimension;
}
float Square::getArea(){
return dimension*dimension;
}
void Square::setDimension(float newDim){
if (newDim<0.0)newDim=0.0;
else dimension=newDim;
}
void Square::setArea(float newArea){
if (newArea<0.0)
newArea=0.0;
else
dimension=sqrt(newArea);
}
Square::Square(){ //set initial dimension to 1.0
dimension=1.0;
}
Square::Square(float initialDim){
initialDim=dimension;
}
This is the main() .cpp client file used to test my functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main(){
Square s1;
Square s2(3.14);
cout << "s1 dimension = " << s1.getDimension() << endl;
cout << "s1 area = " << s1.getArea() << endl;
s1.setDimension(42);
cout << "s1 dimension = " << s1.getDimension() << endl;
cout << "s1 area = " << s1.getArea() << endl;
s1.setArea(49);
cout << "s1 dimension = " << s1.getDimension() << endl;
cout << "s1 area = " << s1.getArea() << endl;
cout << endl;
cout << "s2 dimension = " << s2.getDimension() << endl;
cout << endl;
everything is coming out fine up to the s2 dimension witch is coming out as -1.07374e+000 and should just be 3.14, can anyone tell me what is going on?
Nov 4, 2012 at 3:24pm UTC
1 2 3
Square::Square(float initialDim){
initialDim=dimension;
}
If you look closely at what you're doing there, you'll see that
dimension is not being set, and I would guess your compiler generates a warning that you are ignoring.
Topic archived. No new replies allowed.