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;
}