Addition problem in loop

This is a discussion on Addition problem in loop within the C Programming forums, part of the General Programming Boards category; Hi, I'm a beginner programming and have run into a problem on a project. Here's my loop. while(scanf("%d", &x) != ...

  1. #1
    Registered User
    Join Date
    Jul 2009
    Posts
    15

    Addition problem in loop

    Hi, I'm a beginner programming and have run into a problem on a project. Here's my loop.

    while(scanf("%d", &x) != EOF)
    {
    a = 1 / x;
    b += a;
    c = d / b;

    d++;


    This loop is supposed to calculate the harmonic mean of a number series. The problem here is with the variable "b". I get an error with that because it is not assigned a value. Normally I would set a variable like "b" to 0 when I declare it but since I divided 1 by "x" variable "b" remains 0 for some reason and that's what the loop spits out. What's the problem here?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    If x is an integer, then 1/x is zero. (Well, zero remainder one, but you didn't ask for the remainder, or unless x equals one or zero or negative one.) You need to be using floating-point variables for this.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    What is d initialized to? It would be best if you just posted the entire "working" (ie: broken) program.


    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Registered User
    Join Date
    Jul 2009
    Posts
    15
    Quote Originally Posted by tabstop View Post
    If x is an integer, then 1/x is zero. (Well, zero remainder one, but you didn't ask for the remainder, or unless x equals one or zero or negative one.) You need to be using floating-point variables for this.
    That was the problem. I thought it was something simple I was forgetting. Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. validation problem in a loop (newbie question)
    By Aisthesis in forum C++ Programming
    Replies: 11
    Last Post: 05-10-2009, 11:47 PM
  2. Problem with for loop calling external function
    By lordbubonicus in forum C Programming
    Replies: 2
    Last Post: 10-13-2007, 11:54 AM
  3. For Loop Problem
    By xp5 in forum C Programming
    Replies: 10
    Last Post: 09-05-2007, 05:37 PM
  4. Loop problem
    By Tesnik in forum C++ Programming
    Replies: 29
    Last Post: 08-23-2007, 11:24 AM
  5. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 03:51 PM

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