simple program on loops

This is a discussion on simple program on loops within the C Programming forums, part of the General Programming Boards category; I am trying to get this program to divide and add. it is suppose to add all the (1/limit*limit) up ...

  1. #1
    Unregistered
    Guest

    simple program on loops

    I am trying to get this program to divide and add. it is suppose to add all the (1/limit*limit) up and give a sum. for some reason it gives me an out of 1.0000 every time. Does anybody have any advise or help they can give me..... here is my code....
    Code:
    #include <stdio.h>
    
    int main (void)
    {
    	int limit;
    	float sum=0;
    	int i;
    
    	printf("enter your limit\n");
    	scanf("%d",&limit);
    	printf("your limit is %d\n\n",limit);
    
    	for(i=1;i<=limit;i++)
    	{
    		sum=(1/(i*i))+sum;
    		
    	}
    
    	printf("your total:%f",sum);
    
    	return 0;
    }

  2. #2
    Registered User
    Join Date
    Feb 2002
    Posts
    591
    Well you are getting the problem from integer division. int can not be a decimal number, Try this insted
    Code:
    #include <stdio.h>
    
    int main (void)
    {
    	int limit;
    	double sum=0;
    	double i;
    
    	printf("enter your limit\n");
    	scanf("%d",&limit);
    	printf("your limit is %d\n\n",limit);
    
    	for(i=1;i<=limit;i++)
    	{
    		sum=(1.0/(i*i))+sum;
    		
    	}
    
    	printf("your total:%f",sum);
    
    	return 0;
    }

  3. #3
    Registered User
    Join Date
    May 2002
    Posts
    85
    int limit;
    double sum=0;
    double i; /* i is loop counter */

    For good C programing practice, NEVER make a
    loop control counter with floating point number
    such as float, double..
    Above, the program will work fine as declare
    i as integer (int i). Just add:
    sum = sum + ( 1.0/(i*i) );

    is good enough.

    DV007

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with a very simple program
    By htdefiant in forum C++ Programming
    Replies: 13
    Last Post: 08-14-2007, 01:27 PM
  2. Using variables in system()
    By Afro in forum C Programming
    Replies: 8
    Last Post: 07-03-2007, 12:27 PM
  3. [Help] Simple Array/Pointer Program
    By sandwater in forum C Programming
    Replies: 3
    Last Post: 03-30-2007, 02:42 PM
  4. simple silly program
    By verbity in forum C Programming
    Replies: 5
    Last Post: 12-19-2006, 05:06 PM
  5. Simple simple program
    By Ryback in forum C++ Programming
    Replies: 10
    Last Post: 09-09-2004, 05:48 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21