简体   繁体   中英

How Can I return both number of ints less than or equal to average and number of ints greater than average

I am new to functions. I don't know how can I output numbers of ints less than or equal to average and number of ints greater than average. How I need to call my function so that it output both results ?

int compareAverage(int numbers[], int count, double average)
{
    int lessEqualCount = 0;
    int greaterCount = 0;

    for (int i = 0; i < count; i ++)
       {
           if (numbers[i] <= average){
               lessEqualCount++;
               return lessEqualCount;}


           else{
              greaterCount++;
              return greaterCount;}
       }

There are several solutions.
The first ones that come to my mind:

  • accept to pointers to int in which to write the results
  • return a std::pair of int s instead of a single value
  • return a struct having two properties for the two values
  • return an array (either a naked one or a std::array ) containing the two values
  • ...

It follows an example:

std::pair<int, int> compareAverage(int numbers[], int count, double average) {
    std::pair<int, int> ret = std::make_pair<int, int>(0, 0);

    for (int i = 0; i < count; i ++) {
        if (numbers[i] <= average) {
            ret.first++;
        } else {
            ret.second++;
        }
    }

    return ret;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM