In an exercise, I need to calculate all distances between points of co-ordinates (x,y)
that are read from a file, with the last point coinciding with the first point. Each point represents a city that is represented by the following structure:
typedef struct
{
int x;
int y;
} Cidade;
An example input file can be seen below:
24
(1,10) (4,4) (5,1) (2,0) (1,10)
(1,10) (4,4) (2,0) (5,1) (1,10)
(1,10) (5,1) (4,4) (2,0) (1,10)
(1,10) (5,1) (2,0) (4,4) (1,10)
(1,10) (2,0) (5,1) (4,4) (1,10)
(1,10) (2,0) (4,4) (5,1) (1,10)
(4,4) (1,10) (5,1) (2,0) (4,4)
(4,4) (1,10) (2,0) (5,1) (4,4)
(4,4) (5,1) (1,10) (2,0) (4,4)
(4,4) (5,1) (2,0) (1,10) (4,4)
(4,4) (2,0) (5,1) (1,10) (4,4)
(4,4) (2,0) (1,10) (5,1) (4,4)
(5,1) (4,4) (1,10) (2,0) (5,1)
(5,1) (4,4) (2,0) (1,10) (5,1)
(5,1) (1,10) (4,4) (2,0) (5,1)
(5,1) (1,10) (2,0) (4,4) (5,1)
(5,1) (2,0) (1,10) (4,4) (5,1)
(5,1) (2,0) (4,4) (1,10) (5,1)
(2,0) (4,4) (5,1) (1,10) (2,0)
(2,0) (4,4) (1,10) (5,1) (2,0)
(2,0) (5,1) (4,4) (1,10) (2,0)
(2,0) (5,1) (1,10) (4,4) (2,0)
(2,0) (1,10) (5,1) (4,4) (2,0)
(2,0) (1,10) (4,4) (5,1) (2,0)
I have implemented the two functions below to calculate distances:
float Distancia(Cidade cA, Cidade cB)
{
int distanciaX = pow(cA.x - cB.x, 2);
int distanciaY = pow(cA.y - cB.y, 2);
float distancia = sqrt(distanciaX + distanciaY);
return distancia;
}
float Distancias(Cidade *C, int numeroCidades)
{
int i;
float total = 0;
for(i = 0; i < numeroCidades; i++)
{
if(i == numeroCidades - 1)
{
total = total + Distancia(C[i], C[0]);
}
else
{
total = total + Distancia(C[i], C[i+1]);
}
}
return printf("Distancia Total: %f\n\n", total);
}
Finally, I created another function that stores all these calculated distances:
void ArmazenaDistancias(Cidade C[], int numeroCidade)
{
int i;
float distancias[TotalViagens(numeroCidade)];
for(i = 0; i < TotalViagens(numeroCidade); i++)
{
distancias[i] = Distancias(C, numeroCidade);
}
}
However, when printing the values, all calculated distances are only the result of the first trip. That is, it calculates all 24 trips, but all with the value of the first. Is there something wrong with the functions? I would like to know what can be changed so that each distancias[i]
saves the value of each trip so that, in the end, I can find out the shortest distance (for each different starting city).