gpt4 book ai didi

c - 枚举和一个以字符串形式返回月份名称的函数

转载 作者:行者123 更新时间:2023-12-02 06:13:48 24 4
gpt4 key购买 nike

这是练习:

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;
}

关于c - 枚举和一个以字符串形式返回月份名称的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49438423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com