我正在尝试对数组中的日期进行排序我有以下代码(不包括数组和我正在尝试读取的文件以及另一个包含我正在尝试写入的排序日期的文件。
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.. 行中,它将始终打印相同的日期,我不知道该怎么做才能忽略已经排序的日期。提前致谢。
最佳答案
原始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
前缀,只需分配给现有变量即可。
当您在 C 中说 int x = y;
时,您是在声明一个变量并赋值。分配给现有变量 x = y;
就足够了。
int
前缀仅在变量的第一个实例上是必需的,因此编译器知道对该变量和所有后续引用在同一范围内使用什么类型。
现在通常情况下,编译器会提示在同一范围内创建另一个具有相同名称的变量。在您的情况下,因为您是在 if
中执行此操作,从技术上讲,这是一个不同的范围,因此您可以重复。
关于c - 如何从c中的数组中排序日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53159451/