Thread: loops

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    19

    Unhappy loops

    I'm trying to calculate the average of numbers. In order to do so, I need to get the sum of all the numbers entered. I can't figure out why I'm getting a run-time error. It's counting the number of entries correctly, but I can't get the sum to work. Please help!

    Code:
    void readData(float* num,  float*n, float* sum);
    
    //function main
    int main ()
    {
        // declarations and initializations
            float num=1;
            float n=0;
            float sum=0;
    
        //prompts and scans
            readData(&num,&n,&sum);
        // calculation
        
        // output
    
    
    return 0;
    }
    
    // more functions
    void readData(float*num, float*n, float* sum)
    {
               while (num>0)
            {
               printf("\nEnter a number > 0: ");
               scanf("%f", &num);
               *n=*n+1;
               printf("Number of entries: %f\n",*n);
               *sum=*sum+*num;
                printf("Sum: ", *sum);
            }
    
        return;
    }

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Take a close look at your last printf statement.

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    19
    Ok, I see that I didn't have the %f in there, I changed the statement to this and it still doesn't work

    Code:
    printf("Sum: %f", *sum);
    I also tried it without the *, that didn't work either.

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Oh, I see. You have an ampersand in front of num:
    scanf("%f", &num);

    Which NORMALLY would be fine, BUT now, you brought over a pointer to num. So *num is now num, and num (no *), is a pointer.

    So it's confusing, but remove the ampersand in front of num:
    scanf("%f", num);

    With that change, and the %f in place in your print statement, everything works fine.
    Last edited by Adak; 10-11-2010 at 09:50 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help with loops - super n00b
    By antipesto93 in forum C++ Programming
    Replies: 2
    Last Post: 06-15-2010, 09:57 AM
  2. loops and macros
    By ginom71 in forum C Programming
    Replies: 13
    Last Post: 07-18-2009, 01:04 PM
  3. Too many loops D:
    By F5 Tornado in forum C++ Programming
    Replies: 6
    Last Post: 12-03-2007, 01:18 AM
  4. recoursion or loops?
    By Mecnels in forum C++ Programming
    Replies: 2
    Last Post: 01-14-2002, 12:09 PM
  5. help with arrays and loops
    By jdiazj1 in forum C Programming
    Replies: 4
    Last Post: 11-24-2001, 04:28 PM