Write a function meanDistance which takes a pointer to a list of Pair objects and computes the mean distance of (x, y) to the origin.
实现起来比较容易,下面代码仅供参考:
class Pair {
public:
double x;
double y;
Pair();
Pair(double x, double y);
};
Pair::Pair() :
x(0.0), y(0.0) {
}
Pair::Pair(double x, double y) :
x(x), y(y) {
}
/*
Write a function meanDistance which takes a pointer to a list of Pair
objects and computes the mean distance of (x, y) to the origin.
*/
double meanDistance(list<Pair>* lp) {
double sum = 0.0;
double size = lp->size();
for (Pair &p : *lp) {
sum += pow(p.x * p.x + p.y * p.y, 0.5);
}
return sum/size;
}
void testMeanDistance() {
Pair p1 = { 3,4 };
Pair p2 = { 3,4 };
list<Pair> ps = { p1,p2 };
double sum = meanDistance(&ps);
ASSERT_APPROX_EQUAL(sum, 5.0, 0.0001);
}
系统当前共有 481 篇文章