Question

I am trying to calculate the radius of a ball that can be made if I have leather with 4195065486 mm2 area and 1 mm thickness, starting from a small ball with radius = 1 mm the maker can wrap up the leather as multilayer around the ball. I wrote this code to get the radius of the ball which can be made and the area which will remain from the leather. (assuming that pi=3.14159).

double A, r;
const double pi=3.14159;
double AreaCalc(double r);
int main(){

    A=4195065486.0;
    r=1.0;
    double final_r = AreaCalc(r); 
    cout<<final_r<<"  "<<A<<"  "<<endl;
    return 0;
}

double AreaCalc(double r){
    double ca;

    ca=4*pi*r*r;
    if (A-ca>=0.0){

        A=A-ca;
        AreaCalc(r+1);
    }
    else return r;
}

Is there any truncation or influence which may cause an inaccurate result of A? By debugging i can get A=12559904.940002432.

Was it helpful?

Solution

You're missing a return in the if-branch, causing undefined behaviour.
Add it:

return AreaCalc(r+1);

You should have got a compiler warning for that.
If you didn't, increase your warning level.
If you did, start paying attention to warnings. Your compiler's "Treat warnings as errors" option is a very healthy choice.

(But, like @Henrik suggests in the comments, maths is the best solution.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top