2016-07-22 61 views
2

我写了一个程序,它接收一个日期,然后将其转换为一周中的某一天。当我编译时遇到问题时,我问了一个前面的问题来解决它。如何清理此代码以将日期转换为星期几?

我已经设法解决它与一些非常赞赏的建议,它运行完美。

但是,我很清楚它看起来像一堆狗屎。我通过一本书学习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; 
} 

回答

2

我会做的第一件事就是删除该switch语句,因为它基本上是做dayName = day;

一旦你这样做,你可能也注意到,你不根本不需要dayName变量。您可以直接使用day

+0

真棒,谢谢你@Gibstick! – gloopit

相关问题