[Solved] How to convert string formula in c#? [closed]


First you read the documentation and pretty much code it up as written:

public static double ComputeResult( double diameter , double height )
{
  double result =   0.5
                  * (
                          ( (2.0*height) - diameter )
                        * Math.Sqrt( (height*diameter) - Math.Pow(height,2.0) )
                      +   (diameter/2.0)
                        * Math.Asin( 2.0*height -1.0 )
                        / diameter
                      + ( Math.PI * Math.Pow(diameter,2.0) )
                        / 2.0
                    ) ;
    return result ;
}

Though your formula seems to spit out NaN (not a number) quite a bit.

It’ll be easier to check your computations if you refactor it to evaluate each intermediate computation individually and build up the result as you go along, much like you’d do if working on paper/blackboard/slide rule/calculator.

You’ve got essentially 3 multiplicative expressions that are computed, summed together and divided by 2, so you could break it up into at least 3 pieces (though I’d probably go further):

public static double ComputeResult( double diameter , double height )
{
  double t1 = ( (2.0*height) - diameter )
            * Math.Sqrt( (height*diameter) - Math.Pow(height,2.0) )
            ;
  double t2 = ( diameter / 2.0 )
            * Math.Asin(2.0*height-1.0)
            / diameter
            ;
  double t3 = ( Math.PI * Math.Pow(diameter,2.0) )
            / 2.0
            ;
  double result = 0.5 * ( t1 + t2 + t3 ) ;
  return result ;
}

2

solved How to convert string formula in c#? [closed]