首页 > 解决方案 > 如何在c中对数组中的日期进行排序

问题描述

我正在尝试从数组中对日期进行排序,我有以下代码(不包括数组和我试图读取的文件,另一个是我试图写入的排序日期。

int aniomayor=tot[0].anio;
int diamayor=tot[0].dia;
int mesmayor=tot[0].mes;

while (i<nf) {
  if (tot[i].anio > aniomayor) {
    int aniomayor=tot[i].anio;
    int diamayor=tot[i].dia;
    int mesmayor=tot[i].mes;
  }
  else if (tot[i].anio == aniomayor && tot[i].mes > mesmayor) {
    int aniomayor=tot[i].anio;
    int diamayor=tot[i].dia;
    int mesmayor=tot[i].mes;
  }
  else if (tot[i].anio == aniomayor && tot[i].mes == mesmayor &&  tot[i].dia > diamayor) {
    int aniomayor=tot[i].anio;
    int diamayor=tot[i].dia;
    int mesmayor=tot[i].mes;
  }

  i++;
}

fprintf(f, "%s ", diamayor);
fprintf(f, "%s ", mesmayor);
fprintf(f, "%s \n", aniomayor);

我认为它会起作用,但在 2,3,4.. 行中,它将始终打印相同的日期,我不知道该怎么做才能忽略已经排序的日期。提前致谢。

标签: c

解决方案


原始int声明建立变量。随后的创建具有相同名称但不是相同变量的“影子”变量。

这是一个演示:

#include <stdio.h>

int main() {
  int x = 1;

  if (x == 1) {
    int x = 2;
    printf("x=%d\n", x);
  }

  printf("x=%d\n", x);

  return 0;
}

这打印:

x=2
x=1

顶层x永远不会被修改,因此它似乎恢复为原始值。

您应该从中删除int前缀,只需分配给现有变量。

当您int x = y;在 C 中说时,您是在声明一个变量并分配一个值。分配给现有变量x = y;就足够了。

前缀仅在变量的第一个实例上是必需的int,因此编译器知道该使用什么类型以及同一范围内的所有后续引用。

现在通常编译器会抱怨创建另一个具有相同名称的变量,如果它是在相同的范围内完成的。在您的情况下,因为您是在 内进行的if,从技术上讲,这是一个不同的范围,因此您可以有重复项。


推荐阅读