我的C编码越来越好,但我仍然不确定如何在我的代码中解决几个问题。教授希望我们写一个输入日期的代码(mm / dd / yyyy)并吐出已经过去的天数。对于选择2,输入特定年份的天数并吐出相应的日期。问题是(因为我们的教授喜欢弄乱我们)解决像4/31/2001这样的错误,其中4月没有31天,并且在非闰年输入了366天。
int leap(int x)
{
if ((x % 4 == 0 && x % 100 != 0)|| x % 400 == 0)
return 1;
else
return 0;
}
int monthFun(int d, int y)
{
int days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int i;
if (leap(y))
days[1] = 29;
for (i = 0; ; i++)
if (d > days[i])
d = d - days[i];
else
return i + 1;
return i + 1;
}
int dateFun(int d, int y)
{
int days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int i, m;
if (leap(y))
days[1] = 29;
for (i = 0; i < m - 1; i++)
if (d > days[i]) {
d = d - days[i];
}
else {
d = d;
m = i;
}
return d;
}
int daysPast(int m, int d, int y)
{
int days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int i, past = 0;
if (leap(y))
days[1] = 29;
for (i = 0; i < m - 1; i++)
past = past + days[i];
return past + d;
}
int main()
{
int mm, dd, yy, choice;
char more;
do {
printf ("\n\t\tThis program will find days passed or date in the year");
printf ("\n\t\t\t\t1) Input date (mm/dd/yyyy) to find the days passed");
printf ("\n\t\t\t\t2) Input passed days to find date in the year");
printf ("\n\n\t\t\t\tYour choice (1/2): ");
scanf ("%d", &choice);
if (choice == 1) {
printf ("\n\t\tPlease input date (mm/dd/yyyy): ");
scanf ("%d/%d/%d", &mm, &dd, &yy);
printf ("\n\t\tThere are %d days passed in the year %d", daysPast(mm, dd, yy), yy);
}
else
if (choice == 2){
printf ("\n\t\tInput days: ");
scanf ("%d", &dd);
printf ("\n\t\tInput year: ");
scanf ("%d", &yy);
printf ("\n\t\tThe date is %d/%d/%d", monthFun(dd, yy), dateFun(dd,yy), yy);
}
else
printf ("\n\t\tPlease choose 1 or 2");
printf ("\n\n\t\tDo more (Y/N)? ");
scanf ("%s", &more);
} while (more == 'y' || more == 'Y');
}
我的dateFun()的代码有点草率(或者至少对我而言)。我想如果输入上述问题之一,程序会说“无效输入”之类的东西,并带你回到“做更多”。任何提示都表示赞赏,并提前感谢!
答案 0 :(得分:0)
你的dateFun测试一个未初始化的m。
dateFun()和monthFun()看起来非常相似,我添加了一个示例组合版本。
int leap(int x)
{
return ((x % 4 == 0 && x % 100 != 0)|| x % 400 == 0);
}
int monthFun(int d, int y)
{
int i, days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
days[1] += leap(y);
for (i=0 ; d>days[i] ; i++)
d -= days[i];
return i+1;
}
int dateFun(int d, int y)
{
int i, days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
days[1] += leap(y);
for (i=0 ; d>days[i] ; i++)
d -= days[i];
return d;
}
int datemonthFun(int d, int y)
{
int i, days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
days[1] += leap(y);
for (i=0 ; d>days[i] ; i++)
d -= days[i];
return (i+1)*100+d;
}