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

标签 c++ c++11

所以基本上我的 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/

相关文章:

c++ - 有效地从 n-ary 树中删除节点列表

c++ - 如何调用模板类型的正确构造函数?

c++ - 返回 NULL 值

c++ - 调用 std::stable_sort 时出错?

C++,从字符串到字符数组的转换

c++ - 从指针读取 cubin 结构

c++ - 提取类的模板参数并迭代它们的最紧凑的方法是什么?

C++如何将 vector 与模板一起使用?

c++ - 我可以在 g++ 4.4 中使用 auto 吗?

c++ - 不允许在 C++ 中使用默认构造函数