c - 如何在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.. 行中,它将始终打印相同的日期,我不知道该怎么做才能忽略已经排序的日期。提前致谢。
解决方案
原始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
,从技术上讲,这是一个不同的范围,因此您可以有重复项。
推荐阅读
- node.js - 在 mongoose 中使用查找填充一个集合
- node.js - 通过 Github Push 在 Heroku 中的 NodeJS 应用程序部署错误
- python - Django 无法在管理页面中登录超级用户
- javascript - Aria 选择器在 FB 上找不到元素
- sql - 在 PostgreSQL 中保存多个用于聚合的动态过滤器
- css - 如何在 React 中减少引导程序的表单宽度输入
- css - CSS 会改变 DOM 吗?
- scala - 将 docker 插件与 sbt 一起使用
- javascript - Fetch-api OpenWeather,访问属性“名称”值并显示它的问题
- plugins - 即使在 android 和 Flutter 插件安装设置之后也不会创建 Flutter 应用程序