# Thread: help with a c code

1. ## help with a c code

the question is
Write a program that estimates then prints the value of the mathematical constant e by using the formula:

e=1+ 1/1!+ 2/2! + 3/3!+ ...
(calculate till 5/5!)
my answer
Code:
```#include <stdio.h>

int main()

{

int factorial=1;

float formula;
int counter=0;
float e=0.0;
while(counter<=5)
{
if(counter==0){factorial=1;
counter=counter+1;}
factorial*=counter;
formula=(float)counter/factorial;
e=e+formula;
counter++;
}
printf("%f",e);
return 0;
}```
can any one tell what is wrong here?

2. Originally Posted by hula2007
can any one tell what is wrong here?
You don't indent your code.
You need to tell us what's wrong. Do you get an error, a wrong result, ...?

Bye, Andreas

3. you are incrementing counter twice in the first iteration of the loop but as you are checking <= you get away with that, you dont need to assigin 1 to factorial in the IF statement as it was assigned 1 to start with and the WHILE control is not repeated (which would mean reassignment was neccesary) Your program is a bit clunky and could be cleaner, certainly better formatted, but apart from that it should work ok

Sorry but i dont really understand maths notation, wish i did..dont know what the ! means so i cant figure out your description of the formula relative to the code and tell you if there is a problem, but it could certainly be expressed with one line using appropriate parentheses to get the order right.

4. It probably doesn't help that your mathematical description is wrong. I haven't even checked to see if the code matches the formula.

e = 1 + 1/1! + 1/2! + 1/3! + ..... not 1 + 1/1! + 2/2! + 3/3! + .....

Popular pages Recent additions