0

I am working in a C code for school, the program is supposed to extract an array N of float values and determinate the pairs with the shortest distance between them; when there is only one closest pair of numbers the code prints it properly, however, when there are more (2 or +), is simply doesn't print anything in the result part (I mean, the other sentences like "Type file name" still there, but the "result" is missing).

How can I solve i?

The code is in Spanish, but I'll add the translation

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main() {
char file_name[100];
int n, i;


printf("\tEscriba el nombre del archivo:\n");  //Type file name 
scanf("%s", file_name);

FILE *archivo = fopen(file_name, "r");    //archivo means file
if (archivo == NULL) {
    printf("No se pudo abrir el archivo.\n"); //File error
    return 1;
}

//sacar el valor de n contandoi los elemntos 
float value;
n = 0;
while (fscanf(archivo, "%f\n", &value) != EOF) {
    n++;
}


rewind(archivo);  //inciio


float a[n];
for (int i = 0; i < n; i++) {
    fscanf(archivo, "%f\n", &a[i]);
}


fclose(archivo); //cerrar owo

//algoritmo de selección para el orden :3
for (int i = 0; i < n - 1; i++) {
    int maxIndex = i;
    for (int j = i + 1; j < n; j++) {
        if (a[j] > a[maxIndex]) {
            maxIndex = j;
        }
    }
   
    float temp = a[i];
    a[i] = a[maxIndex];
    a[maxIndex] = temp;
}

//valores ordenados
printf("\nValores ordenados de mayor a menor:\n");    //Values sorted from + to -
for (int i = 0; i < n; i++) {
    printf("%.2f, ", a[i]);
  
}

  printf("\n");

  int distanceSize = n - 1;

  float distancia[distanceSize];       //distancia means distance (between pair of numbers)

// distancia directa lineal pq si no revuelve todo 
printf("\nDistancia: \n");      //Distance
for (i = 0; i < distanceSize; i++) {
    distancia[i] = a[i] - a[i + 1];
    printf("%.2f, ", distancia[i]);
}

   
//ordenar distancia 
 for (i = 0; i < distanceSize; i++) {
    for (int j = 0; j < distanceSize - i - 1; j++) {
        if (distancia[j] > distancia[j + 1]) {
            float temp = distancia[j];
            distancia[j] = distancia[j + 1];
            distancia[j + 1] = temp;
        }
    }
}  //burbuja pq nu me salió el otro aquí



printf("\n\nValores ordenados de la distancia:\n");   //Sorted distance values 
for (i = 0; i < distanceSize; i++) {
    printf("%.2f, ", distancia[i]);
}


float min = distancia[0];

 // printf("\n%.2f\n", distancia[0]);
  printf("\n\nDistancia Min: %.2f\n", min);

printf("\nPARES CERCANOS\n");      //CLOSEST PAIRS (HERE IS WHERE IT PRINTS NOTHING WHEN THERE ARE MORE THAN 1 PAIR WITH THE SAME DISTANCE)

for (i = 0; i < n; i++) {
  if (a[i + 1] - a[i] == min) {
    printf("(%.2f, %.2f)", a[i], a[i + 1]);
  }
}
return 0;
}
akaay
  • 11
  • 4
  • 1
    Post the (smallest) input data set that shows the bug – Support Ukraine Jun 26 '23 at 08:27
  • Please do yourself and everyone else a favor and apply some proper and consistent indentation. It makes the code way more readable. – Gerhardh Jun 26 '23 at 08:33
  • See the linked question for full description. The short explanation is that floats can't represent every value so some rounding is likely to happen on you input. Try data like `{6.0 , 5.6, 1.9 , 2.3}` and print the distance with e.g. 20 decimal. See https://ideone.com/drSXVq – Support Ukraine Jun 26 '23 at 08:54
  • OT: `qsort` and `fabs` would have made your program much simpler. – Support Ukraine Jun 26 '23 at 08:56

1 Answers1

0

This for loop

for (i = 0; i < n; i++) {
  if (a[i + 1] - a[i] == min) {
    printf("(%.2f, %.2f)", a[i], a[i + 1]);
  }
}

results in accessing memory outside the array a when i is equal to n - 1 due to expression a[i + 1].

The second problem with the loop is that as the array a is sorted in the descending order then the expressioin a[i + 1] - a[i] always has a non-positive value while min is always a non-negative value.

Rewrite the loop like

for ( i = 1; i < n; i++) {
  if (a[i - 1] - a[i] == min) {
    printf("(%.2f, %.2f)", a[i - 1], a[i]);
  }
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335