### Route distance

The input is a sequence of routes. Every route starts with a word that identifies it, and then, there is a sequence of two or more pairs of doubles that represent the coordinates of the visited places. The final point always coincides with the starting point, and it appears only at the beginning and in the end of each sequence of coordinates.

My program must print the total Euclidean distance of each route given, following the format of the instance. The distances must be written with 4 digits behind the dot.

 ``12345678910111213141516171819202122232425262728293031`` ``````#include #include using namespace std; double distance(double x1, double y1, double x2, double y2) { return sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)); } int main () { string name; double x_ini, y_ini, x, y, px, py; while (cin >> name) { double x_ini, y_ini; px = x_ini; py = y_ini; bool end = false; double total = 0; while (cin>>x>>y and not end) { total = total + distance(px, py, x, y); if (x == x_ini and y == y_ini) end = true; px = x; py = y; } cout.setf(ios::fixed); cout.precision(4); cout << "Route " << name << ": " << total << endl; } }``````

The programs calculate the distance ok, but when I execute it it only works for the first distance, after the first distance it ends when you try to imput something else, and It souldn't becaouse of the while cin >> name
@Line 11: You never initialize x_ini and y_ini. That might cause some issues.

@Line 14: You never initialize these x_ini and y_ini either, which will be used instead of the ones on line 11. Was this intentional?

-Albatross
oh that is true indeed, I will try it again, thanks :)

But anyways, do think that is the reason it is not looping?
Could be. Who knows what your program will do when those two aren't initialized? It's undefined behavior.

-Albatross
Still I modified it so that the first values are the initial x and y but it will not work anyways... :(

 ``1234567891011121314151617181920212223242526272829303132`` ``````#include #include using namespace std; double distance(double x1, double y1, double x2, double y2) { return sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)); } int main () { string name; double x_ini, y_ini, x, y, px, py; while (cin >> name) { double x_ini, y_ini; cin >> x_ini >> y_ini; px = x_ini; py = y_ini; bool end = false; double total = 0; while (cin>>x>>y and not end) { total = total + distance(px, py, x, y); if (x == x_ini and y == y_ini) end = true; px = x; py = y; } cout.setf(ios::fixed); cout.precision(4); cout << "Route " << name << ": " << total << endl; } }``````
Topic archived. No new replies allowed.