Tag Archives: #WSQ12

Homework 12: Estimating e

This program will be capable of estimate the value of “Euler’s number” (e) and the user will give the accuracy expressed as a number of decimals.

To calculate e, I declared three variables. One of them saves tha value of e, another counts each executation of the loop, and the last one (x), in each ocassion is multiplied by the counter, an then divides the number one (1) to be added to e.

This process is into a loop that is executed a big number of times, I made it to be repeated 999,999,999,999,999,999 times. And obviously, all this is a function.

Finally, in the main funtion, I ask the user for the accuracy of e, and I interpret it as the number of decimals. I show that quantity of decimals using printf(“%.*Lf\n\n\n”,a,calculate_e()),  where the asterisk allows to specify the the decimal is a variable called “a”. The letters “Lf” indicates that the type of the value (long double) and the period after “%” indicates that we are modifying the number of printed decimals.

Having said that, I’ll show you my code…

#include <iostream>
#include <cmath>
#include <stdio.h>
using namespace std;

long double calculate_e(void)
{
  long double e=1, x=1 , i=1;
  while(x<999999999999999999)
  {
    x*=i;
    e+=1/x;
    i++;
  }
  return e;
}

int main() {
  int a;
  cout << "\n\nLet's to calculate 'e'...\n";
  cout << "ACCURACY (Number of decimals between 1 and 50): ";
  cin >> a;
  printf("%.*Lf\n\n\n",a,calculate_e() );
  return 0;
}