Skip to main content
Contents
Dark Mode Prev Up Next Scratch ActiveCode Profile
\(
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section 8.5 Structures as parameters
You can pass structures as parameters in the usual way. For example,
void printPoint(Point p) {
cout << "(" << p.x << ", " << p.y << ")" << endl;
}
printPoint takes a point as an argument and outputs it in the standard format. If you call
printPoint (blank), it will output
(3, 4).
Listing 8.5.1. This active code uses the printPoint function. Run the code to see the output!As a second example, we can rewrite the
distance function from
SectionΒ 5.2 so that it takes two
Points as parameters instead of four
doubles.
double distance(Point p1, Point p2) {
double dx = p2.x - p1.x;
double dy = p2.y - p1.y;
return sqrt (dx*dx + dy*dy);
}
Listing 8.5.2. This active code uses the updated version of the distance function. Feel free to modify the code!
Checkpoint 8.5.1 .
struct Coordinate {
int x, y;
};
void printOppositeCoordinate(Coordinate p) {
cout << "(" << -p.y << ", " << -p.x << ")" << endl;
}
int main() {
Coordinate coord = { 2, 7 };
printOppositeCoordinate (coord);
}
Take a close look at the printOppositeCoordinate function.
Take a close look at the printOppositeCoordinate function.
Yes, this is the correct output.
Take a close look at the Coordinate struct.
Checkpoint 8.5.2 .
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.
void printAveragePoint(Point p1, Point p2, Point p3) {
---
double avgX = (p1.x + p2.x + p3.x)/3;
---
double avgY = (p1.y + p2.y + p3.y)/3;
---
double avgY = (y.p1 + y.p2 + y.p3)/3; #distractor
---
cout << "(" << avgX << "," << avgY << ")";
---
cout << "(" << "avgX" << "," << "avgY" << ")"; #distractor
---
}
You have attempted
of
activities on this page.