幂和平方根不适用于 C++ 中的 assert()
Power and Square Root not working with assert() in C++
这里显示了两个函数:
https://pastebin.com/QWQ6yH6u
// main() calls both findDistance() and test() correctly so they don't need to be shown.
// Note: This is only a section of the full code as it is the only relevant part.
double findDistance(float x1, float y1, float x2, float y2) {
double distanceTotal = sqrt( pow( 2, (x2-x1) ) + pow( 2, (y2-y1) )); // This line doesn't work with assert values.
//double distanceTotal = (x2-x1) + (y2-y1); // This line works with assert values.
return distanceTotal;
}
void test() {
assert(findDistance(4, 3, 5, 1) - 2.23607 <= epsilon);
assert(findDistance(2, 4, 2, 4) <= 1.00);
assert(findDistance(4, 4, 4, 4) <= 1.00);
cout << "all tests passed..." << endl;
}
findDistance 函数正在计算两点 (x1, y1), (x2, y2) 之间的距离。一行与 assert() 值一起正常工作,而包含平方根和幂的那一行则不能。第 5 行有什么问题?
代码使用 http://cpp.sh 编译成功,当前代码的输出为:
Do you want to run the program? (y/n) y
Program calculates distance between 2 points on a 2D coordinates.
Enter a point in the form (x, y): (3,3)
(x1, y1) = (3.00, 3.00)
Enter a second point in the form (x, y): (1,1)
(x2, y2) = (1.00, 1.00)
我已经查看了以下帖子:
1.
2. Square root line doesn’t work
3.
错误是由于std::pow()
的错误使用造成的。这应该会更好:
double distanceTotal = sqrt( pow( (x2-x1),2 ) + pow( (y2-y1), 2 )); // This line doesn't work with assert values.
这里显示了两个函数: https://pastebin.com/QWQ6yH6u
// main() calls both findDistance() and test() correctly so they don't need to be shown.
// Note: This is only a section of the full code as it is the only relevant part.
double findDistance(float x1, float y1, float x2, float y2) {
double distanceTotal = sqrt( pow( 2, (x2-x1) ) + pow( 2, (y2-y1) )); // This line doesn't work with assert values.
//double distanceTotal = (x2-x1) + (y2-y1); // This line works with assert values.
return distanceTotal;
}
void test() {
assert(findDistance(4, 3, 5, 1) - 2.23607 <= epsilon);
assert(findDistance(2, 4, 2, 4) <= 1.00);
assert(findDistance(4, 4, 4, 4) <= 1.00);
cout << "all tests passed..." << endl;
}
findDistance 函数正在计算两点 (x1, y1), (x2, y2) 之间的距离。一行与 assert() 值一起正常工作,而包含平方根和幂的那一行则不能。第 5 行有什么问题?
代码使用 http://cpp.sh 编译成功,当前代码的输出为:
Do you want to run the program? (y/n) y
Program calculates distance between 2 points on a 2D coordinates.
Enter a point in the form (x, y): (3,3)
(x1, y1) = (3.00, 3.00)
Enter a second point in the form (x, y): (1,1)
(x2, y2) = (1.00, 1.00)
我已经查看了以下帖子:
1.
错误是由于std::pow()
的错误使用造成的。这应该会更好:
double distanceTotal = sqrt( pow( (x2-x1),2 ) + pow( (y2-y1), 2 )); // This line doesn't work with assert values.