passing array of structure through function
Feb 15, 2019 at 6:54pm UTC
I'm supposed to write a function that finds the maximum distance between two points created by an array. I'm confused about how to make a function that can pass an array of a structure and find the distance between point x and y?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
#include <iostream>
#include <iomanip>
#include <cmath>
#include <ctime>
#include <cstdlib>
using namespace std;
struct Point {
double x, y;
};
double getDistance(struct Point a, struct Point b);
double random(unsigned long int & seed);
int main()
{
unsigned long int seed;
srand(time(NULL));
seed = rand();
const int SIZE=50;
Point array[50];
for (int i=0; i<SIZE; i++)
{
array[i].x = -5+(10*random(seed));
array[i].y = -5+(10*random(seed));
cout << array[i].x << endl;;
cout << array[i].y << endl;
}
cout <<" Max Distance between a and b: %lf\n" << endl ;
return 0;
}
double random(unsigned long int & seed)
{
const int MODULUS = 15749;
const int MULTIPLIER = 69069;
const int INCREMENT = 1;
seed = ((MULTIPLIER*seed)+INCREMENT)%MODULUS;
return double (seed)/MODULUS;
}
double getDistance(struct Point array ) // help needed
{
double distance;
return distance;
}
Feb 15, 2019 at 7:00pm UTC
Pass it like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
double getDistance(Point array[], int size) // help needed
{
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
double dx = array[i].x - array[j].x;
double dy = array[i].y - array[j].y;
// etc.
double distance = std::sqrt(dx * dx + dy * dy);
}
}
return 0.0; // todo
}
call it like this:
double distance = getDistance(array, SIZE);
cash wrote: maximum distance between two points created by an array.
If that's the case, then "getDistance" is an ambiguous choice for a function name.
I would prefer something like "getMaxDistance".
Last edited on Feb 15, 2019 at 7:03pm UTC
Feb 15, 2019 at 7:03pm UTC
Your function prototype:
double getDistance(struct Point a, struct Point b);
1 2 3 4 5
double getDistance(struct Point array ) // help needed
{
double distance;
return distance;
Doesn't match your function definition in terms of the arguments passed to the function
Feb 16, 2019 at 4:39pm UTC
A minor improvement to Ganado 's excellent suggestion. To avoid checking each pair of points twice, change line 5 to:
for (int j = i+1 ; j < size; j++)
Topic archived. No new replies allowed.