3 Replies - 486 Views - Last Post: 10 November 2010 - 06:25 PM Rate Topic: -----

#1 Matty919  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • 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  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2957
  • View blog
  • Posts: 10,181
  • 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.
Was This Post Helpful? 2
  • +
  • -

#3 Matty919  Icon User is offline

  • D.I.C Head

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

Re: [C] Calculating e

Posted 10 November 2010 - 06:02 PM

View PostCTphpnwb, 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

Was This Post Helpful? 0
  • +
  • -

#4 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2957
  • View blog
  • Posts: 10,181
  • 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.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1