代码不要在数值重复时打印数值。

huangapple go评论64阅读模式
英文:

Code do not print values when are repeated

问题

I've translated the comments in the code for you:

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

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

    printf("\tEnter file name:\n");  // 输入文件名:
    scanf("%s", file_name);

    FILE *archivo = fopen(file_name, "r");  // archivo表示文件
    if (archivo == NULL) {
        printf("Could not open the file.\n");  // 文件错误
        return 1;
    }

    // 获取n的值并计算元素个数
    float value;
    n = 0;
    while (fscanf(archivo, "%f\n", &value) != EOF) {
        n++;
    }

    rewind(archivo);  // 重置

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

    fclose(archivo);  // 关闭文件

    // 选择排序算法 :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;
    }

    // 排序后的值
    printf("\nValues sorted from highest to lowest:\n");  // 从高到低排序后的值:
    for (int i = 0; i < n; i++) {
        printf("%.2f, ", a[i]);
    }

    printf("\n");

    int distanceSize = n - 1;

    float distancia[distanceSize];  // distancia表示距离(数对之间的)

    // 直线距离因为否则会弄乱一切
    printf("\nDistance:\n");  // 距离:
    for (i = 0; i < distanceSize; i++) {
        distancia[i] = a[i] - a[i + 1];
        printf("%.2f, ", distancia[i]);
    }

    // 距离排序
    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;
            }
        }
    }  // 冒泡排序因为其他的我做不出;

    printf("\n\nSorted distance values:\n");  // 排序后的距离值:
    for (i = 0; i < distanceSize; i++) {
        printf("%.2f, ", distancia[i]);
    }

    float min = distancia[0];

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

    printf("\nCLOSEST PAIRS\n");  // 最近的数对 (当有多对距离相同时,这里什么都不打印)

    for (i = 0; i < n; i++) {
        if (a[i + 1] - a[i] == min) {
            printf("(%.2f, %.2f)", a[i], a[i + 1]);
        }
    }
    return 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 &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;
#include &lt;math.h&gt;
int main() {
char file_name[100];
int n, i;
printf(&quot;\tEscriba el nombre del archivo:\n&quot;);  //Type file name 
scanf(&quot;%s&quot;, file_name);
FILE *archivo = fopen(file_name, &quot;r&quot;);    //archivo means file
if (archivo == NULL) {
printf(&quot;No se pudo abrir el archivo.\n&quot;); //File error
return 1;
}
//sacar el valor de n contandoi los elemntos 
float value;
n = 0;
while (fscanf(archivo, &quot;%f\n&quot;, &amp;value) != EOF) {
n++;
}
rewind(archivo);  //inciio
float a[n];
for (int i = 0; i &lt; n; i++) {
fscanf(archivo, &quot;%f\n&quot;, &amp;a[i]);
}
fclose(archivo); //cerrar owo
//algoritmo de selecci&#243;n para el orden :3
for (int i = 0; i &lt; n - 1; i++) {
int maxIndex = i;
for (int j = i + 1; j &lt; n; j++) {
if (a[j] &gt; a[maxIndex]) {
maxIndex = j;
}
}
float temp = a[i];
a[i] = a[maxIndex];
a[maxIndex] = temp;
}
//valores ordenados
printf(&quot;\nValores ordenados de mayor a menor:\n&quot;);    //Values sorted from + to -
for (int i = 0; i &lt; n; i++) {
printf(&quot;%.2f, &quot;, a[i]);
}
printf(&quot;\n&quot;);
int distanceSize = n - 1;
float distancia[distanceSize];       //distancia means distance (between pair of numbers)
// distancia directa lineal pq si no revuelve todo 
printf(&quot;\nDistancia: \n&quot;);      //Distance
for (i = 0; i &lt; distanceSize; i++) {
distancia[i] = a[i] - a[i + 1];
printf(&quot;%.2f, &quot;, distancia[i]);
}
//ordenar distancia 
for (i = 0; i &lt; distanceSize; i++) {
for (int j = 0; j &lt; distanceSize - i - 1; j++) {
if (distancia[j] &gt; distancia[j + 1]) {
float temp = distancia[j];
distancia[j] = distancia[j + 1];
distancia[j + 1] = temp;
}
}
}  //burbuja pq nu me sali&#243; el otro aqu&#237;
printf(&quot;\n\nValores ordenados de la distancia:\n&quot;);   //Sorted distance values 
for (i = 0; i &lt; distanceSize; i++) {
printf(&quot;%.2f, &quot;, distancia[i]);
}
float min = distancia[0];
// printf(&quot;\n%.2f\n&quot;, distancia[0]);
printf(&quot;\n\nDistancia Min: %.2f\n&quot;, min);
printf(&quot;\nPARES CERCANOS\n&quot;);      //CLOSEST PAIRS (HERE IS WHERE IT PRINTS NOTHING WHEN THERE ARE MORE THAN 1 PAIR WITH THE SAME DISTANCE)
for (i = 0; i &lt; n; i++) {
if (a[i + 1] - a[i] == min) {
printf(&quot;(%.2f, %.2f)&quot;, a[i], a[i + 1]);
}
}
return 0;
}

答案1

得分: 0

这个for循环

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

i等于n - 1时,访问了数组a之外的内存,因为表达式a[i + 1]

循环的第二个问题是,由于数组a按降序排列,所以表达式a[i + 1] - a[i]始终具有非正值,而min始终具有非负值。

重写循环如下

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

This for loop

for (i = 0; i &lt; n; i++) {
if (a[i + 1] - a[i] == min) {
printf(&quot;(%.2f, %.2f)&quot;, 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 &lt; n; i++) {
if (a[i - 1] - a[i] == min) {
printf(&quot;(%.2f, %.2f)&quot;, a[i - 1], a[i]);
}
}

huangapple
  • 本文由 发表于 2023年6月26日 16:19:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76554809.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定