1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Easy program

  1. Jul 20, 2010 #1
    i know this is a super easy program, but for some reason it's not working the way i want it to

    Code (Text):

    // prompt user to enter several GPA's then find the average
    // while the user's input is not the sentinel value, -1, add it to the sum
    #include <iostream>

    using namespace std;

    int main(){
        double GPA = 0;
        double sum = 0;
        double count = 0;
        double average = sum / count;

        while (GPA != -1){
            cin >> GPA;
            sum += GPA;
            if (GPA != 1){
                count++;
            }
        }
        cout << average;
        return 0;
    }
     
     
  2. jcsd
  3. Jul 20, 2010 #2

    Zryn

    User Avatar
    Gold Member

    For programs like this, its easy to create output statements for the value of variables as the math progresses. You can then imput simple numbers that you can calculate the program output value for on paper and compare them to the answer the program gives, then work backwards to find the error.

    Where in your program does the 'average' variable get changed from its initialisation value of 'sum / count' to ... anything else ... before it is output ?
     
  4. Jul 20, 2010 #3
    First off, you are doing your average calculation before any input is given. In the declarations, put only "double average;" and after your while loop terminates, put "average = sum/count;"

    Second, count should go up if GPA != -1, not if GPA != 1

    third, (though this isn't ruining your program), I would make count an integer since it only ever accepts integer values. During the average calculation, the double divided by an integer will automatically convert the integer to a double to do double division and store that double in average.
     
  5. Jul 20, 2010 #4

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Ditto what they said.

    It's also probably not a good idea to initialize average to the value 0/0.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Easy program
  1. Verilog Program (Replies: 0)

  2. The program R (Replies: 2)

  3. MARIE Programming (Replies: 1)

  4. Programming question (Replies: 6)

  5. Matlab Programming (Replies: 5)

Loading...