8.5. Structures as parameters¶
You can pass structures as parameters in the usual way. For example,
void print_point (point p) {
cout << "(" << p.x << ", " << p.y << ")" << endl;
}
print_point
takes a point as an argument and outputs it in the
standard format. If you call print_point (blank)
, it will output
(3, 4)
.
The active code below uses the print_point
function. Run the code to
see the output!
As a second example, we can rewrite the distance
function from
Section [distance] so that it takes two point
s as
parameters instead of four double
s.
double distance (point p1, point p2) {
double dx = p2.x - p1.x;
double dy = p2.y - p1.y;
return sqrt (dx*dx + dy*dy);
}
The active code below uses the updated version of the distance
function.
Feel free to modify the code!
- (-2.0, -7.0)
- Take a close look at the print_opposite_coordinate function.
- (2.0, 7.0)
- Take a close look at the print_opposite_coordinate function.
- (-7.0, -2.0)
- Yes, this is the correct output.
- (7.0, 2.0)
- Take a close look at the print_opposite_coordinate function.
Q-3: What will print?
struct coordinate {
double x, y;
};
void print_opposite_coordinate (point p) {
cout << "(" << -p.y << ", " << -p.x << ")" << endl;
}
int main() {
coordinate coord = { 2.0, 7.0 };
print_opposite_coordinate (coord);
}
Construct a function that takes in three point structures and prints the average of the x coordinates and the average of the y coordinates as a coordinate. Find the x average before the y average.