Thread: Annoying Array - Simple Problem ( I hope)

  1. #1
    Registered User
    Join Date
    Nov 2011
    Location
    Boston, MA
    Posts
    7

    Annoying Array - Simple Problem ( I hope)

    Hey guys, I'm working on what should be a fairly simple program. This is a function I'm having trouble with. It's probably some stupid mistake but if so I can't see it. I want the function to set each variable in an array to a fraction (decimal), but each value after arrays[0] ends up as 0. I'm pretty sure the problem lies within the function after checking the variables while debugging.

    Code:
    double init(double arrays[], int n)
    {
        int counter;
        for (counter = 0; counter <= n; counter++)
        {
        arrays[counter] = 1 / (counter + 1);
        }
        return 0;
    }
    I want the array's values to be set like this:

    a[0] = 1/1, a[1] = 1/2, a[2] = 1/3 ... a[n] = 1/(n+1)

    Any help is greatly appreciated!

    EDIT: I doubt this will help but I started the function in main() using this line: init(arrays, n);
    Last edited by Parrot; 11-05-2011 at 05:04 PM.

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    They will all end up as 0 since integers don't support decimal places, only whole numbers.

    You need to do this with floating point math...
    Code:
    arrays[counter] = 1.0 / (counter + 1);
    You won't actually see 1/4 etc. you will see the decimal equivalent .25.

  3. #3
    Registered User
    Join Date
    Nov 2011
    Location
    Boston, MA
    Posts
    7
    Ohhh, so apparently I needed a 1.0 instead of 1 in my equation.

    I tried it and it seems to work fine. I knew it was something simple like that! Thanks!
    Last edited by Parrot; 11-05-2011 at 07:06 PM.

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Parrot View Post
    Ohhh, so apparently I needed a 1.0 instead of 1 in my equation.

    I tried it and it seems to work fine. I knew it was something simple like that! Thanks!
    Yeah, it will do it as an integer unless there's a floating point number in there someplace...

    You're welcome.

  5. #5
    Registered User
    Join Date
    Nov 2011
    Posts
    161
    Quote Originally Posted by Parrot View Post
    Ohhh, so apparently I needed a 1.0 instead of 1 in my equation.
    And if you're short on memory, 1. will work too

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple problem, I hope...
    By Polaris84 in forum C Programming
    Replies: 15
    Last Post: 02-25-2011, 06:06 PM
  2. Replies: 2
    Last Post: 04-22-2009, 02:35 AM
  3. Replies: 5
    Last Post: 12-03-2003, 05:47 PM
  4. annoying problem, solution should be simple...
    By Captain Penguin in forum C++ Programming
    Replies: 0
    Last Post: 10-18-2002, 04:41 PM
  5. Replies: 1
    Last Post: 07-20-2002, 06:33 PM