Thread: Help with program harmonic series

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    25

    Help with program harmonic series

    I have tried to code the following harmonic series as below but the progrma outputs 1.000000 only, could someone point out where the flaw is ?

    1+1/2+1/3+...........+1/n

    Code:
    #include<stdio.h>
    #include<conio.h>
    void main()
    {
    int n,deno;
    printf("enter the value of n");
    scanf("%d",&n);
    deno=1;
    float sum = 0;
    while(deno<=n)
    {
    sum=sum+(1/deno);
    deno++
    )
    printf("%f",sum);
    getch()
    }

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    When deno is an int, 1/deno uses integer math and the result for any nonzero deno will be zero. Try 1.0/deno.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Dec 2005
    Posts
    25
    Quote Originally Posted by Dave_Sinkula
    When deno is an int, 1/deno uses integer math and the result for any nonzero deno will be zero. Try 1.0/deno.
    But 'sum' I thought is of type float and the whole expression is
    real expression and hence the right hand side of the assignment operator sum=sum+(1/deno) should be of type float ,isnt it ?

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    No. Reread my reply.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  5. #5
    Registered User
    Join Date
    Dec 2005
    Posts
    25
    Quote Originally Posted by Dave_Sinkula
    No. Reread my reply.

    heh ok

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 02-21-2008, 10:39 AM
  2. Using variables in system()
    By Afro in forum C Programming
    Replies: 8
    Last Post: 07-03-2007, 12:27 PM
  3. BOOKKEEPING PROGRAM, need help!
    By yabud in forum C Programming
    Replies: 3
    Last Post: 11-16-2006, 11:17 PM
  4. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM