Help with simple program

Discussion in 'C++' started by Steve18, Oct 17, 2008.

  1. Steve18

    Steve18 New Member

    Joined:
    Oct 17, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    I'm very new to programming and ive been trying to figure out this problem for a few days and still have no luck, I cant figure out how to get the average to ignore an out of range number. Also the range is the max- the min which i cant get to work either please help.

    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
    double x;
    double sum = 0.0;
    int number = 0;
    double average;
    double max = 0;
    double min = 0;
    
    while (cin>>x)
    
    {
    if ((x < 0) || (x > 100))
    {
    cin.ignore(3,'\n');
    
    cout << "Out of range ; ignored." << endl;
    }
    
    if (x > max)
    max = x;
    
    if (min > x)
    x = min;
    
    sum += x;
    number++;
    }
    if (number > 0)
    {
    average = sum / number;
    cout<<"The average is "<< average;
    cout<<" The range is "<< max - min;
    cout << endl;
    }
    return 0;
    }
     
    Last edited by a moderator: Oct 17, 2008
  2. asha

    asha New Member

    Joined:
    Nov 9, 2006
    Messages:
    44
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    Homemaker
    Location:
    Kolkata
    Home Page:
    http://whatanindianrecipe.com
    What's the objective of the program??
     
  3. oogabooga

    oogabooga New Member

    Joined:
    Jan 9, 2008
    Messages:
    115
    Likes Received:
    11
    Trophy Points:
    0
    You're starting min at 0, so nothing will be less than it. You need to start it at the maximum (100).

    You need to add "continue;" after the out of range check to skip the rest of the while loop:
    Code:
    if ((x < 0) || (x > 100))
    {
        cin.ignore(99,'\n');
        cout << "Out of range ; ignored." << endl;
        continue;
    }
    The line x = min needs to be min = x.
     
    shabbir likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice