# [C] Calculating e

Page 1 of 1

## 3 Replies - 992 Views - Last Post: 10 November 2010 - 06:25 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=199466&amp;s=a66ee16d37e338191258809b8f8f963b&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Matty919

Reputation: 1
• Posts: 83
• Joined: 10-May 09

# [C] Calculating e

Posted 10 November 2010 - 05:32 PM

Formula:

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

I am trying to do this without the use of a function.

The code:

```
/*
Name: PP6_11.c
Author: Matt
*/

#include <stdio.h>

int main(void)
{
int n, i, m, fact = 1;
float e = 1;

printf("Enter n: ");
scanf("%d", &n);

for(i = 1; i <= n; i++)
{
m = i;
while ( m > 1)
{
fact = fact * m;
m = m - 1;
}
e = e + 1/fact;
}

printf("e = %0.2f.\n", e);

return 0;
}

```

I get the answer of 2.00 every time though and am not sure why.

This post has been edited by Matty919: 10 November 2010 - 05:33 PM

Is This A Good Question/Topic? 0

## Replies To: [C] Calculating e

### #2 CTphpnwb

• D.I.C Lover

Reputation: 3389
• Posts: 11,999
• Joined: 08-August 08

## Re: [C] Calculating e

Posted 10 November 2010 - 05:40 PM

This:

```e = e + 1/fact;

```

has a constant integer (1) divided by an integer (fact). When (fact) is 1, we have e+1 = 2, then when (fact) is greater than 1, 1/fact is 0, so 2+ 0 is always 2.
Change to:

```e = e + 1.0/fact;

```

to force the compiler to interpret this as a float/integer.

### #3 Matty919

Reputation: 1
• Posts: 83
• Joined: 10-May 09

## Re: [C] Calculating e

Posted 10 November 2010 - 06:02 PM

CTphpnwb, on 10 November 2010 - 04:40 PM, said:

This:

```e = e + 1/fact;

```

has a constant integer (1) divided by an integer (fact). When (fact) is 1, we have e+1 = 2, then when (fact) is greater than 1, 1/fact is 0, so 2+ 0 is always 2.
Change to:

```e = e + 1.0/fact;

```

to force the compiler to interpret this as a float/integer.

Works now, thanks.

So when an integer is divided by a float the answer is given as an integer?

This post has been edited by Matty919: 10 November 2010 - 06:02 PM

### #4 CTphpnwb

• D.I.C Lover

Reputation: 3389
• Posts: 11,999
• Joined: 08-August 08

## Re: [C] Calculating e

Posted 10 November 2010 - 06:25 PM

When an int is divided by an int, it returns an int. A float divided by an int will return a float. That's why using 1.0 instead of 1 gets the desired result.