【问题标题】:C++ nested switches duplicate value errorC++嵌套开关重复值错误
【发布时间】:2020-11-08 15:19:10
【问题描述】:

所以这是我试图开始工作的代码,但它在到达 B 时显示“重复大小写值” 我是大学一年级的学生,所以我可能使用了错误的格式,或者我可能忽略了一些我似乎真的没有弄清楚问题的地方,所以我向你们寻求帮助


char dep;
 int exp;
 
 cout<<"please enter your department, A, B OR C: ";
 cin>>dep;
 
 cout<<"please enter your years of experience ";
 cin>>exp;
 
switch(dep)
 {
    
        case 'A' || 'a' :{
                             switch (exp) {
                                case 5:
                                    cout<<"you will recieve a 5% raise and 2.5% extra due to your experience";
                                break;
                                defualt : cout<<"you get 5% raise";
                                break;
                               }
            
          }     
        break;
        
        case 'B' || 'b' :{
                            switch (exp) {
                                case 5:
                                cout<<"you will recieve a 2% raise and 2.5% extra due to your experience";
                                break;
                                defualt : cout<<"you get 2% raise";
                                break;
                               }
          }
        break;

【问题讨论】:

  • case 'A' || 'a' 是错误的。使用 2 个 case 代替 case 'A`: case 'a':
  • case 'A' || 'a' - 不是语言的工作方式。你需要两个案例。一个可能是另一个。例如case 'A'; case 'a': 正如所写的那样,您对true 有两个测试。仅供参考,嵌套与此无关。
  • 'A' || 'a''B' || 'b' 都为真(非零值被隐式转换为真),所以你得到两个case true:,编译器输出错误。
  • 对于这么简单的事情,我宁愿推荐dep = std::tolower(dep); if (dep == 'a') { /* Code for A */ } else if (dep == 'b') { /* Code for B */ } else { /* Neither */ }
  • @Someprogrammerdude 他们当然应该写一个。

标签: c++ switch-statement valueerror


【解决方案1】:

虽然它可以编译(或者没有B 版本),并且如果粗略地翻译成英文,可以拼出你想要的东西,case 'A' || 'a' 并没有按照你的想法做。

case 之后的表达式被视为选择语句的完全匹配 - it's compared exactly to dep。您不能输入更复杂的表达式并期望它被“展开”到多重比较中。将switch/case 视为一个简单的查找表,而不是智能分支功能(这就是if 的用途!)。

也许令人困惑的是,表达式 'A' || 'a' 本身是有效的,但(与任何表达式一样)它的计算结果为单个值:truefalse,这取决于任一操作数是否“真实” ”。在这个特定的示例中,ASCII 值都不为零,因此两者都是真实的,并且表达式始终为 trueIt'll be converted to the type of dep (the rules say it becomes 1) 并用于精确查找。

既然您也使用了'B''b',那么you do then indeed have two equivalent cases

相反,为每个条件编写一个单独的案例。幸运的是,由于cases fall through,你不需要重复案例的“主体”:你可以将两个cases并排放置;只是不要在它们之间放置break

case 'A':
case 'a':
   // code here
   break;

case 'B':
case 'b':
   // code here

顺便说一句,你拼错了default

【讨论】:

  • ohhhhhhhh 我明白了,我不知道这会是一个问题,非常感谢你
  • @Kas-per 你打赌。
猜你喜欢
  • 2011-08-15
  • 1970-01-01
  • 1970-01-01
  • 2011-09-29
  • 1970-01-01
  • 1970-01-01
  • 2010-12-30
  • 1970-01-01
  • 2019-01-28
相关资源
最近更新 更多