开发者

Return two values from a function? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

returning multiple values from a function

There is this exercise I have, and it says that I have to make a function that will read with appropriate inducements the height and number of hits a ball hits the ground.

How can a function return two values? Doesn't it only return one? What will it r开发者_开发知识库eturn?

float insert(int h,int n)
{
   printf ("Give a value for height and number of hits");
   scanf ("%d %d",&h,&n);
   return
}


As an aside, the function you give returns nothing which is an error.

A function can have only a single return value. If you want to return multiple values you can:

  1. Return a struct containing the values.
  2. Pass the return values as parameters using pointers.

An example of the option 2:

void divmod(int a, int b, int *div, int *mod)
{
    *div = a/b;
    *mod = a%b;
}

Call the function like this:

int div;
int mod;
divmod(666, 42, &div, &mod);

I intentionally chose a different example because I couldn't work out what you want to do with your float return value.


For a homework assignment, they'll probably be happy with you passing in the parameters to fill in.

void insert(int* h, int* n)
{
   ...
   scanf("%d %d", h, n);
}

// called like:
// int height, number;
// insert(&height, &number);

But you can always get tricky and return a struct

typedef struct
{
  int h;
  int n;
} S;

S insert()
{
  S s;
  ...
  scanf ("%d %d" , &s.h, &s.n);
  return s;
}


You can either return a struct that encapsulates the two values, or use two pointer parameters in which the function will store the values.

typedef struct
{
    double height;
    int hits;
} BallParameters;


BallParameters insert()
{
    BallParameters ret;
    printf ("Give a value for height and number of hits");
    scanf ("%f %d",&ret.height,&ret.hits);
    return ret;
}

/* ~~~ or ~~~ */

void insert(double *height, int *hits)
{
    printf ("Give a value for height and number of hits");
    scanf ("%f %d",height,hits);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜