Function giving wrong values

2

For some reason, my function of calculating distances is giving wrong values sometimes. Not only that, but the values seem to be from memory addresses (since they are very large), but I'm not sure if that's it. The function:

float distancia(int ax, int ay, int bx, int by) // Calcula a distancia entre dois pontos, onde eh respectivamente (X1 Y1), (X2 Y2)
{
    return(sqrt((pow((ax - bx), 2)) + (pow((ay - by), 2))));  
}

One of the functions that calls the above function. It writes in a txt document and the values printed there go wrong:

void arquivoDistancia(float matrizDistancia[][30])
{
    FILE *aquivoDeSaida;
    int cont = 0, cont2 = 0;

    aquivoDeSaida = fopen("distancia.txt", "w");
    while( cont < 30 ) //loop para gravar os dados no arquivo.
    {
        while( cont2 < 30 ) //loop para gravar os dados no arquivo.
        {   
           fprintf(aquivoDeSaida, "%.2f ", matrizDistancia[cont][cont2]); //grava garacter a caracter no arquivo apontado por custo.
           cont2++;      
        }
        fprintf(aquivoDeSaida, "\n");
        cont++;
        cont2 = 0;      
    }
    fclose(aquivoDeSaida); 


} 

and this is the function that makes the arrayDistance [] [30]. Notice that I even put a printf to see the values. The problem starts here by the way. It prints everything right at the beginning but then strange numbers begin to appear

void mDistancia(char cidadeXY[][150], int coordenadasX[], int coordenadasY[], float matrizDistancia[][30])
{
    int c, i, contadorC, contadorI;
    float dij; 

    for(i = 0, contadorI = 0; i < 30; i++, contadorI += 2)
    {
        for(c = 0, contadorC = 0; c < 30; c++, contadorC += 2)
        {
            dij = distancia(coordenadasX[contadorI], coordenadasY[contadorI], coordenadasX[contadorC], coordenadasY[contadorC]);
            printf("%.2f ", dij);
            matrizDistancia[i][c] = dij;
        }
    }

}
    
asked by anonymous 08.12.2014 / 01:15

2 answers

4

It's good to keep in mind that signing sqrt() informs you that it returns a double . When trying to save your result to a float variable you may end up losing information, which would justify the problem you observed.

On the other hand, sqrtf() returns a float , which would be more appropriate in your case.

    
08.12.2014 / 02:18
1
for(i = 0, contadorI = 0; i < 30; i++, contadorI += 2)
//                                     ^^^^^^^^^^^^^^
{
    for(c = 0, contadorC = 0; c < 30; c++, contadorC += 2)
    //                                     ^^^^^^^^^^^^^^
    {
        dij = distancia(coordenadasX[contadorI], coordenadasY[contadorI], coordenadasX[contadorC], coordenadasY[contadorC]);

Why do the variables contadorI and contadorC advance by 2 in 2?

In this way you will never calculate the distances between points with odd indexes; and you will be accessing (probably) non-existent elements of the arrays.

    
08.12.2014 / 09:09