即使代码完成,为什么还在更改var?

时间:2017-03-14 21:19:09

标签: c variables printf

代码说明: 我的代码询问用户2000年之后的日期,它会一直询问,直到用户输入0/0/0作为日期。我的代码应该只存储输入的最低日期。

#include <stdio.h>

main(){
 int m, d, y, mm, dd, yy, loop = 1, trial = 0;

 while(loop != 0){
  printf("Enter a date (mm/dd/yy): ");

  if(trial == 0){                              //Just to store in value for dd, mm, yy for the first time
    scanf("%d/%d/%d", &mm, &dd, &yy);
    if(dd == 0 && mm == 0 && yy == 0){         //If on the first attempt they put in 0/0/0, end the code
      return 0;
    }
    trial++;                                  //To stop this trial
  }
  else{
    scanf("%d/%d/%d", &m, &d, &y);            //Hold the new inputted value
  }

  if(d == 0 && m == 0 && y == 0){             //Ending the code after first trial
    printf("%d/%d/%d is the earliest date", mm, dd, yy);
    return 0;
  }

  if(y <= yy){                                //Changing the stored variable 
    yy = y;

    if(m <= mm){
      mm = m;

      if(d <= dd){
        dd = d;
      }
    }
  }
 }

 return 0;
 }

我输入了这个,我把它作为输出:

Enter a date (mm/dd/yy):  01/05/06
Enter a date (mm/dd/yy):  0/0/0
1/5/0 is the earliest date   

出于某种原因,它正在改变我不希望它做的那一年。我正在考虑更改代码,以便将日期更改为天,然后,它将比较它以查看更小的代码。我甚至试图更改代码,但这不起作用。

1 个答案:

答案 0 :(得分:2)

代码中的问题是y没有值。因此,代码会将y解释为y = 0。即使你这样做,代码中仍然存在问题。您试图存储最低日期,但代码只存储最小的数字。因此,您应该将代码改为:

if(y < yy){ 
    yy = y;
    mm = m;
    dd = d;
  }

  if(y = yy){
    if(m < mm){
      yy = y;
      mm = m;
      dd = d;
    }

    if(m == mm){
      if(d < dd){
        yy = y;
        mm = m;
        dd = d;
      }

      if(d == dd){
        yy = y;
        mm = m;
        dd = d;
      }
    }
  }

}