这是练习:

Write a function called monthName() that takes as its argument a value of type enum month (as defined in this chapter) and returns a pointer to a character string containing the name of the month. In this way, you can display the value of an enum month variable with a statement such as:

printf("%s\n", monthName(aMonth));

我编写了我的版本并获得了预期的输出。但是,我确信必须有更好的方法来实现这一点,而不必每个月都使用一个 case 的 switch 语句。我怎样才能用更好的设计来编写这个函数?

#include <stdio.h> 
 
enum month { January = 1, February, March, April, May, June,  
        July, August, September, October, November, December }; 
 
char *monthName(enum month m){ 
    switch (m) { 
        case January: 
            return "January"; 
            break; 
        case February: 
            return "February"; 
            break; 
        case March: 
            return "March"; 
            break; 
        case April: 
            return "April"; 
            break; 
        case May: 
            return "May"; 
            break; 
        case June: 
            return "June"; 
            break; 
        case July: 
            return "July"; 
            break; 
        case August: 
            return "August"; 
            break; 
        case September: 
            return "September"; 
            break; 
        case October: 
            return "October"; 
            break; 
        case November: 
            return "November"; 
            break; 
        case December: 
            return "December"; 
            break; 
        default: 
            return "Not a valid month"; 
    } 
} 
 
int main(void) 
{ 
    enum month aMonth = 1; 
 
    printf("%s\n", monthName(aMonth)); 
 
    aMonth = 2; 
    printf("%s\n", monthName(aMonth)); 
 
    aMonth = 6; 
    printf("%s\n", monthName(aMonth)); 
 
    return 0; 
} 

请您参考如下方法:

您可以使用一个简单的查找表,因为枚举以 1 开头:

#include <stdio.h> 
 
enum month { January = 1, February, March, April, May, June,  
        July, August, September, October, November, December }; 
 
const char *months_str[] = { 
    "January", "February", "March", "April", "May", "June", "July", 
    "August", "September", "October", "November", "December", NULL 
}; 
 
const char *monthName(enum month m) { 
    if(m < January || m > December) 
        return "Invalid month"; 
 
    return months_str[m-1]; 
} 
 
int main(void) 
{ 
    enum month aMonth = 1; 
 
    printf("%s\n", monthName(aMonth)); 
 
    aMonth = 2; 
    printf("%s\n", monthName(aMonth)); 
 
    aMonth = 6; 
    printf("%s\n", monthName(aMonth)); 
 
    return 0; 
} 


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!