我编写了一个程序,它接受日期,然后将其转换为一周中的某一天。当我编译遇到问题时,我问了一个上一个问题来修复它。
我已经通过一些非常感谢的建议成功修复了它,并且运行完美。
但是,我很清楚它看起来像一堆狗屎。我正在通过一本书学习 C,并且没有涉及指针或字符串,因此我可以用来简洁地构造该程序的内容非常有限。
我假设这本书希望我在不使用该语言的这些方面的情况下完成此练习。
有没有什么我遗漏的东西可以让我缩短这个时间?
这是代码:
#include <stdio.h>
typedef struct
{
int day;
int month;
int year;
}DATE;
int nConvert(DATE N);
int gee(DATE work);
int eff(DATE work);
int dayFinder(int N);
int main (void)
{
int N, day, dayName;
DATE date;
char names[7][3] = {
{'S', 'u', 'n'},
{'M', 'o', 'n'},
{'T', 'u', 'e'},
{'W', 'e', 'd'},
{'T', 'h', 'u'},
{'F', 'r', 'i'},
{'S', 'a', 't'}
};
printf("Okay, choose your date:\n");
scanf("%i/%i/%i", &date.day, &date.month, &date.year); //puts the date and creates a variable withing the DATE struct
N = nConvert(date); //go convert the date into an integer
day = dayFinder(N); //go convert N into an int that represents the day of the week
//now we match the int from dayFinder and match it to the right array in names so it can then be printed below
switch(day)
{
case(0):
dayName = 0;
break;
case(1):
dayName = 1;
break;
case(2):
dayName = 2;
break;
case(3):
dayName = 3;
break;
case(4):
dayName = 4;
break;
case(5):
dayName = 5;
break;
case(6):
dayName = 6;
break;
}
// now we can print out the day of the week that we created in dayFinder
printf("The day of the week of %i/%i/%i is: %c%c%c\n", date.day, date.month, date.year, names[dayName][0], names[dayName][1], names[dayName][2]);
}
int nConvert(DATE N)
{
int f = eff(N); //call the functions so the outputs can be put into the equation for 'result'
int g = gee(N);
int result = (1461 * f) / 4 + (153 * g) / 5 + N.day; //store the result of the equation into a 'result'
return result; //go put result back into main, will be called 'N'
}
int eff(DATE work)
{
if(work.month <= 2)
{
work.year = work.year - 1;
}
else
{
work.year = work.year;
}
return work.year;
}
int gee(DATE work)
{
if(work.month <= 2)
{
work.month = work.month + 13;
}
else
{
work.month = work.month + 1;
}
return work.month;
}
int dayFinder(int n)
{
int convert = (n - 621049) % 7; //convert N sent from main, into integer called converter.
//we will now have a number that conincides with the day of the week
return convert;
}
最佳答案
我要做的第一件事就是删除该 switch 语句,因为它本质上是在执行 dayName = day;
完成此操作后,您可能还会注意到您甚至根本不需要 dayName
变量。您可以直接使用day
。
关于c - 如何清理此代码以将日期转换为一周中的某一天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38516715/