简体   繁体   中英

Calculating e number C#

I am trying to calculating e number by that

e = 1 + (1/1! + 1/2! + 1/3! + ..)

User going to select number of trials on that form. form

 int trialNumber = Convert.ToInt32(Math.Round(trialNumberForm.Value, 0));
        int factorial = trialNumber;
        float factResult = 0;

        for (int i = 1; i < trialNumber; i++)
        {

            for (int b = 1; b < i; b++) //calculates x! here.
            {
                factorial = factorial * b;


            }
           factResult = factResult + (1 / factorial);
        }
        factResult++;
        MessageBox.Show(factResult.ToString());

It calculates the result 1 which ever number you selected! I've tried to change variable type to float from double but that didn't fix it. How to act on numbers by formula which I wrote above?

You have no need in factorial (with its integer division and integer overflow problems) at all since

  1/(n+1)! == (1/n!)/(n+1)

You can implement e computation as easy as

  double factResult = 1; // turn double into float if you want
  double item = 1;       // turn double into float if you want

  for (int i = 1; i < trialNumber; ++i)
    factResult += (item /= i);

  ...

  MessageBox.Show(factResult.ToString());

Outcomes:

   trial number | e
   -------------------------------
              1 | 1
              2 | 2
              3 | 2.5
              4 | 2.666666... 
              5 | 2.708333...
             10 | 2.71828152557319
             15 | 2.71828182845823 
             20 | 2.71828182845905

As @kabdulla and @ScottChamberlain said, you are doing integer division where you need a float division :

for (int b = 1; b < i; b++) //calculates x! here.
{
    factorial = factorial * b;
}
factResult = factResult + (1 / factorial);

Should be

for (int b = 2; b < i; b++) //calculates x! here.
{
    factorial = factorial * b;
}
factResult = factResult + (1.0 / factorial);

Plus I started the for loop at b = 2 because multiplying by 1 is useless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM