My Computer Forum Computer Science Forum

Go Back   My Computer Forum > Computer Science Forum > Programming

Programming Programming Languages, Interpreters, and Compilers - Assembly, Declarative, Machine, Object Oriented, Iterative


Reply
 
LinkBack Thread Tools Display Modes
July 13th, 2010, 02:48 AM   #1
 
Joined: Oct 2008
Posts: 16
C code bummer

Code:
#include <stdio.h>

int main()
{
	int i;
	double sum = 1.0;

	for (i = 1; i < 10001; i++)
			sum += 1/(2*i) - 1/(2*i + 1);
	
       printf("==> %f\n", sum);
}
Output: Nothing but 1.000000, what's wrong? :x
greg1313 is offline  
 

My Computer Forum is free to register and we welcome everyone!

July 13th, 2010, 06:01 AM   #2
Retired
 
Joined: Jul 2010
Posts: 23
Re: C code bummer

Two words, integer division. Because your equation was using 1 and 2 instead of 1.0 and 2.0 and the fact that i was also an int meant your loop was adding 0 every time. Simple fix, either change i to double, as I did below, or change your constants in the equation to 1.0 and 2.0 to force floating point arithmetic.

Code:
#include <stdio.h>

int main()
{
   double i;
   double sum = 1.0;

   for (i = 1.0; i < 10001.0; i += 1.0)
         sum += 1/(2*i) - 1/(2*i + 1);
   
       printf("==> %f\n", sum);
}
shynthriir is offline  
July 13th, 2010, 03:11 PM   #3
 
Joined: Oct 2008
Posts: 16
Re: C code bummer

Great, thanks.
greg1313 is offline  
Reply

  My Computer Forum > Computer Science Forum > Programming

Tags
bummer, code



Thread Tools
Display Modes


Similar Threads
Thread Thread Starter Forum Replies Last Post
simple pari-GP code question billymac00 Programming 0 November 8th, 2013 05:32 AM
Javascript to CSS code bulf Tech Support 1 December 18th, 2011 02:42 PM
C++ program code, need help with this C++ application. chetanbhasin Programming 0 June 17th, 2010 07:57 PM
html code to display message when a webpage loads... chetanbhasin Programming 3 June 10th, 2010 05:43 AM
genetic code setayesh94 Computer Science 0 February 6th, 2010 04:33 AM





Copyright © 2017 My Computer Forum Forum. All rights reserved.