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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



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



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





Post code here, not via sites such as pastebin.
– Neil Butterworth
15 mins ago





@NeilButterworth I did post the code here too..
– PiggiesGoSqueal
12 mins ago





Are you sure you want to compute 2 ^ (delta x) and 2 ^ (delta y)?
– tkausl
7 mins ago




1 Answer
1



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


std::pow()


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






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard