Home > Enterprise >  How to calculate the average score in struct function of C ?
How to calculate the average score in struct function of C ?

Time:10-31

This is the question that I was aasigned. https://i.stack.imgur.com/efRFk.png

And this is my coding. This is my first time asking question here so I dont really know how to paste my coding here. https://i.stack.imgur.com/QCOBG.png

I really hope someone can help me out. Thank you.

CodePudding user response:

You have to initialize the variable "sum"

When you run the code, "sum" is created in the memory.

but it has no value if you don't initialize with value such as 0, 1, 2 ... anything you want.

then, "sum" will take any value which exist in the assigned memory.

that's why the sum of "sum" has junk value.

Thus, you have to initialize "sum" as below.

double sum =0.0;

CodePudding user response:

You can use the below shown program as a starting point(reference). In your program you were creating an ordinary(nonmember) double named average while according to the assignment average should be a data member as shown below. Second, there is no need to create a separate variable called sum because you can use variable average to sum all the test scores and then divide average by 3 which is also shown below.

#include <iostream>

struct Result
{
    public:
        //this takes input from user
        void takeTestInput()
        {
            for(int i = 0; i < sizeof(test)/sizeof(int);   i)
            {
                std::cout<<"Input#"<<i 1<<": ";
                std::cin >> test[i];//take the input and put into test[i]
            }
        }
        
        void calculateAverage()
        {
            
            for(int i = 0; i < sizeof(test)/sizeof(int);   i)
            {
                average =test[i];    
            }
            average = average/3; 
        }
        
        void printAverage()
        {
            std::cout<<average;
        }
    private:
        int test[3];
        double average; //data member called average 
};

int main()
{
    Result student1;
    
    //take input for student1
    student1.takeTestInput();
    
    //calculate average for student1
    student1.calculateAverage();
    
    //check if the average calculated above is correct by printing out the average for student1
    student1.printAverage();
    return 0;
}

The output of the above program can be seen here.

  • Related