Avg program in c

Discussion in 'Mac Programming' started by dukebound85, Oct 5, 2006.

Thread Status:
Not open for further replies.
  1. dukebound85 macrumors P6

    dukebound85

    Joined:
    Jul 17, 2005
    Location:
    5045 feet above sea level
    #1
    never mind i figured it out

    this can be a wastelanded
     
  2. YoNeX macrumors regular

    YoNeX

    Joined:
    Apr 29, 2005
    #2
    #include <iostream>

    using namespace std;

    int main(){

    int num;
    int avg = 0;
    int avg_count = 0;

    do
    {
    cout << "Enter in a number to average or -1 to terminate: ";
    cin >> num;
    if(num > 0)
    {
    avg += num;
    avg_count++;
    }
    }
    while(num >0);

    cout << "Your average is: " << avg / avg_count << endl;

    return 0;
    }

    EDIT: Guess I posted this too late.
     
  3. bousozoku Moderator emeritus

    Joined:
    Jun 25, 2002
    Location:
    Gone but not forgotten.
    #3
    You should think about doing excellent programmes, not just average ones. ;)
     
  4. dukebound85 thread starter macrumors P6

    dukebound85

    Joined:
    Jul 17, 2005
    Location:
    5045 feet above sea level
    #4

    Good call. Always nice to see a different way to accomplish the same thing.

    Haha yea only excellent programs here on out


    what does the += do in your if function. thanks
     
  5. balamw Moderator

    balamw

    Staff Member

    Joined:
    Aug 16, 2005
    Location:
    New England
    #5
    Code:
    avg += num;
    is shorthand for

    Code:
    avg = avg + num;
    B
     
  6. YoNeX macrumors regular

    YoNeX

    Joined:
    Apr 29, 2005
    #6
    Now, if you want to store each value, the best way is arrays.

    It would be something like int avg_num[9999]; Then you just set the assign the number to each of the avg_num (i.e. avg_num[0] = 1; avg_num[1] = 5). But in this case, no real use for storing the values anyways.

    In this case, I used vectors: http://www.cs.ucr.edu/~ttaing/gpa_calculator.php . Just a GPA calculator, but takes the same idea as averaging values and reading in string to determine the value. As you can see, I can make the code run more efficently, but I'm not too worried about that. There are numerous ways to solve your problem, right now, just worry about getting it right, then optimizing the code later.
     
Thread Status:
Not open for further replies.

Share This Page