gpt4 book ai didi

c++ - 需要帮助让我的开关盒看起来更好

转载 作者:太空宇宙 更新时间:2023-11-03 10:24:57 25 4
gpt4 key购买 nike

所以基本上我的 switch case 可以工作,但我的教授说返回太多,“使用可变结果,然后在最后返回它!”

这是我的代码

int getMonthValue(){
switch(month){
case(1): //January
if(isLeapYear(year) == true)
return 6;
else
return 0;
case(2): // February
if(isLeapYear(year) == true)
return 2;
else
return 3;
case(3): //March
return 3;
case(4): //April
return 6;
case(5): //May
return 1;
case(6): //June
return 4;
case(7): //July
return 6;
case(8): //August
return 2;
case(9): //September
return 5;
case(10): //October
return 0;
case(11): //November
return 3;
case(12): //December
return 5;}

};

我看不出有什么问题,我相信它可以写得更好。有人能告诉我一种以更用户友好的方式格式化它的方法吗?我的教授还希望我在 switch 中使用 break,不知道为什么要使用 break over return。

最佳答案

在您的情况下使用逻辑运算符不是一个好主意。使用数组!这段代码很好理解,而且速度非常快。而且很容易改变返回值:

unsigned getMonthValue(unsigned month, unsigned year) {
const static unsigned ans[2][12] = {
// Jan F M A M J J A S O N Dec
{0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5 } //normal year
, {6, 2, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5 } //leap year
};
assert(month <= 12);
assert(month >= 1);
const size_t month_index = month - 1;
const size_t leap = isLeapYear(year) ? 1 : 0;
return ans[leap][month_index];
}

更新

有关此技术的链接非常有用 - Lookup_table .感谢Schwern !

关于c++ - 需要帮助让我的开关盒看起来更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39813635/

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