I’m using xcode v. 4.5.1 and trying to calculate the distance between two points using the distance formula (sqrt( (x1-x2)^2 + (y1-y2)^2 )) for a C++ project but for some reason my values are not being squared. Why is this happening and how do I square a value?
source here is a vector of point objects. The vector I’m working with is (3,4) (6,8) (50,8) (11,7). If I print source[i], source[i+1] or source[j] with .x() or .y() at the end, they all print out appropriately, and when I print out source[i].x()-source[i+1].x(), etc. the values are correct. BUT once I add the “^2”, the values printed are all wrong.
For example,
cout<< source[i].y(); shows 4 8 8 7 (when looped over i)
BUT
cout<< sqrt((source[i].x()-source[i+1].x())^2 + (source[i].y()-source[i+1].y())^2);
shows 1 when i=1
Here are my includes:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include "Point.h"
Here is the portion of code that won’t square values for me:
void function(vector<Point>& source){
if(source.size()>3){
for(int i=0; i<n+2; i++){
for(int j=i+2; j<n; j++){
double d1 = sqrt((source[i].x()-source[i+1].x())^2 + (source[i].y()-source[i+1].y())^2);
double d2 = sqrt((source[i].x()-source[j].x())^2 + (source[i].y()-source[j].y())^2);
if( d1 > d2){
swap( source[i+1], source[j] );
}
}
}
}
When you want to raise your answer by a power, which in your case, you are squaring, you need to use the pow function.
To learn more about the function, you can type “man pow” in the Terminal.app application.
So, for one line, you may want to change it to: