Power and Square Root not working with assert() in C++

2507 views c++
-2

I have two functions shown here: 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;
}

The findDistance function is finding the distance between two points (x1, y1), (x2, y2). One line works properly with the assert() values while the one containing square roots and powers does not. What is wrong with line 5?

The code compiles successfully using http://cpp.sh and the output with the current code is:

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) 

I've already checked the following posts: 1. How to calculate power in C 2. Square root line doesn’t work 3. C++ Square Root Function Bug

answered question

Post code here, not via sites such as pastebin.

@NeilButterworth I did post the code here too..

Are you sure you want to compute 2 ^ (delta x) and 2 ^ (delta y)?

1 Answer

2

The error is due to the wrong use of std::pow(). This should work much better:

double distanceTotal = sqrt( pow( (x2-x1),2 ) + pow( (y2-y1), 2 )); // This line doesn't work with assert values.

posted this

Have an answer?

JD

Please login first before posting an answer.