Returning struct member from function

I am attempting to read info from a file, calculate averages, and return the lowest percentage and the occupation associated with it. The program originally used a void function but I have been instructed modify the program to use a struct. I have tried returning the variable holding the calculation but I get a compiler error saying that conversion from struct to double isn't possible.

This is the function looking for the lowest percentage.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  Occupation findLow(Occupation occupations[], int rows)
{
    double avgLow = 0.0;
    double lowPercent;
    string occu;
    lowPercent = occupations[0].numSusceptible / occupations[0].numEmployed;

    // Loop while 'i' has not reached 'rows'
    for (int i = 0; i < rows ; i++)
    {
        // Divide second row of 'occupations' array by contents of first row of 'occupations'
        // array. Store results into 'avgLow' array.
        avgLow = (float)occupations[i].numSusceptible / occupations[i].numEmployed;
        // Find the occupation with the lowest susceptibility for automation
        // and set 'lowPercent' and 'occupation' to these values.
        if (avgLow < lowPercent)
        {
            lowPercent = avgLow;
            occu = occupations[i].occupation;
        }
    }
    lowPercent *= 100;
} // End of findLow 
Last edited on
What sort of struct are you wishing to return?

If the output information is just lowPercent and occu then you could return these as reference arguments.

If, on the other hand, you want to return an "Occupation" then you need to keep tabs on the index associated with the lowest percent and then return that particular occupation[] element at the end.

So, it isn't clear exactly what you want.


Smaller things:
- occu isn't necessarily set; initialise it immediately after initialising lowPercent on line 6.
- use (double), not (float), on line 13.
- avgLow isn't an array (line 12); is this your comment or a requirement?
- comments shouldn't "state the bleedin' obvious".


Last edited on
You have no return statement.

It seems that your function should be used:
1
2
3
4
5
6
7
Occupation findLow(Occupation occupations[], int rows);


Occupation foo[N];
// initialize foo
Occupation low = findLow( foo, N );
// use low 

If you promise to return an Occupation, then that is what you should return:
1
2
3
4
Occupation findLow(Occupation occupations[], int rows)
{
  return occupations[0];
}

Ok, that result is not necessarily the "lowest" and what if rows==0?

How about returning index:
1
2
3
4
5
6
7
8
9
int findLow(Occupation occupations[], int rows)
{
  return 0;
}


// use
int low = findLow( foo, N );
double lowP = 100.0 * occupations[low].numSusceptible / occupations[low].numEmployed;

Topic archived. No new replies allowed.