C++ 如何在 Switch 语句中使用 IF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11505438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:12:12  来源:igfitidea点击:

How to use IF in Switch statement

c++switch-statementaverage

提问by Mustafa Muhammad Yousif

How to apply if condition in Switch statement, I want to calculate Average: however I have tried for best to solve the issue but still getting no output from Switch statement. I am beginner to the C++,

如何在 Switch 语句中应用 if 条件,我想计算平均值:但是我已经尽力解决了这个问题,但仍然没有从 Switch 语句中得到任何输出。我是 C++ 的初学者,

#include <iostream>

using namespace std;

int main()
{
    //declaration of variables.
    int sub1,sub2,sub3, sub4,sub5,total,avg;

    //accepting marks from user in each subject
    cout << " Enter Programming in C++ Marks: " << endl;
    cin >> sub1;
    cout << " Enter Software Engineering Marks : " << endl;
    cin >> sub2;
    cout << " Enter Personal Communication Marks : " << endl;
    cin >> sub3;
    cout << " Enter Database Application Marks: " << endl;
    cin >> sub4;
    cout << " Enter Computer Concept Marks: " << endl;
    cin >> sub5;

    //calculatin sum of marks obtained in each subject
    total = (sub1 + sub2 + sub3 + sub4 + sub5);

    //calculating the average marks
    avg = total / 5;

    // starting of if condition for finding out grades of total subjects.

    switch (avg){
      case 1:{
        if ((avg >= 80) && (avg <= 100))
        {
            cout << " Your Average is: " << avg << endl;
            cout << "You Grade is A+ " << endl;
        }
        break; 
      }
      case 2:{
        if ((avg >= 70) && (avg <= 79))
        {
            cout << " Your Average is: " << avg << endl;
            cout << " Your grade is A " << endl;
        }    
        break;
      } 
      case 3:{
        if ((avg >= 60) && (avg <= 69))
        { 
            cout << " Your Average is: " << avg << endl;
            cout << " Your Grade is B+  " << endl;
        }   
        break;  
      }
      case 4:{
        if ((avg >= 50) && (avg <= 59))
        {
            cout << " Your Average is: " << avg << endl;
            cout << " Your Grade is C+ " << endl;
        }
        break;
      }
      case 5: {
        if ((avg >= 40) && (avg <= 49))
        {
            cout << " Your Average is: " << avg << endl;
            cout << " Your Grade is  C- ! " << endl;
        }
        break;    
      }
      case 6: {
        if ((avg >= 30) && (avg <= 39))
        {
            cout << " Your Average is: " << avg << endl;
            cout << " Your Grade is  D ! " << endl;
        }
        break; 
      }

      default:{ 
        if ((avg >= 100) && (avg <= 29))
        {
            cout << " Your Average is: " << avg << endl;
            cout << " Your Grade is  F, So you are Fail in the class ! " << endl;
            break;
        }
      }
    }

    system("pause");
}

回答by Joey

Well, switchcompares the cases with the variable you gave it. So for case 1it tries comparing avgto 1and afterthat it would go on with your ifstatement, which, of course, would never apply.

好吧,switchcases 与您提供的变量进行比较。因此,对于case 1它试图比较avg,以1之后,它会去与你的if声明,其中,当然,绝不会适用。

I'm not really sure what you're trying there; from all I can see you're better off with a nested if:

我不太确定你在那里尝试什么;从我所看到的,你最好使用嵌套的if

if ((avg >= 80) && (avg <= 100))
{
  cout << " Your Average is: " << avg << endl;
  cout << "You Grade is A+ " << endl;
} else if ((avg >= 70) && (avg <= 79))
{
  cout << " Your Average is: " << avg << endl;
  cout << " Your grade is A " << endl;
} else if ((avg >= 60) && (avg <= 69))
{ 
  cout << " Your Average is: " << avg << endl;
  cout << " Your Grade is B+  " << endl;
} ...

But even that can be handled more elegantly, depending on your skills. For example, you can divide the average by 10 and use switchon that, exploiting the fact that integer division truncates, collapsing everything between 50and 59into the same bucket 5:

但即使这样也可以更优雅地处理,这取决于您的技能。例如,您可以除以10平均值,并使用switch上,利用这样的事实整数除法截断,倒塌之间的一切50,并59进入同一个桶5

switch (avg / 10) {
  case 10:
  case 9:
  case 8:
    cout << " Your Average is: " << avg << endl;
    cout << "You Grade is A+ " << endl;
    break;
  case 7:
    cout << " Your Average is: " << avg << endl;
    cout << "You Grade is A " << endl;
  ...
}

Also you'll notice that you print ?Your average is: ...? every time, so you can move that line beforethe conditions:

你还会注意到你打印 ? 你的平均值是:...?每次,因此您可以在条件之前移动该行:

cout << " Your Average is: " << avg << endl;
switch (avg / 10) {
  ...
}

Finally, since you have a quite small list of possible outcomes, you can collect them in an array and simply reference the appropriate array element, without even needing an if/else ifor switch:

最后,由于您有一个非常小的可能结果列表,您可以将它们收集在一个数组中并简单地引用适当的数组元素,甚至不需要if/else ifswitch

char[][] grades = {
  "F", "F", "F", "D", "C-", "C+", "B+", "A", "A+", "A+", "A+"
};
char[] grade;
if (avg > 100)
  grade = "F";
else
  grade = grades[max(0, avg / 10)];

cout << " Your average is " << avg << endl;
cout << " Your grade is " << grade << endl;

回答by brismith

The switch statement is used to execute one block of code dependent on a particular value. In a sense, the switch statement can be thought of as a form of an if statement: the code

switch 语句用于根据特定值执行一个代码块。从某种意义上说,switch 语句可以被认为是 if 语句的一种形式:代码

switch (avg) {
   case 1 : { /* code block 1 */ } break;
   case 2 : { /* code block 2 */ } break;
   default : { /* code block default */ } break;
}

can be read as

可以读作

if (1 == avg) { /* code block 1 */ }
else if (2 == avg) { /* code block 2 */ }
else { /*code block default */ }

Your switch statement can be read as

您的 switch 语句可以读作

if (1 == avg) 
{
   if ((avg >= 80) && (avg <= 100))
   {
      cout << " Your Average is: " << avg << endl;
      cout <<  "You Grade is A+ " << endl;
   }
} else if...

and there's no way avg can == 1 and be greater than 80 and less than 100, which is why you don't get any output.

并且 avg 不可能 == 1 并且大于 80 且小于 100,这就是您没有得到任何输出的原因。

In C++, the switch statement doesn't lend itself well to testing for ranges; I'd just use an if statement:

在 C++ 中,switch 语句不能很好地测试范围;我只是使用 if 语句:

if ( (avg<=100) && (avg >=80))
{
   // you get an A
} else if ...

But, if you really really need to use a switch, there are a few ways to go about it:

但是,如果你真的需要使用 switch,有几种方法可以解决这个问题:

switch (avg) {
   case 100:
   case 99:
   case 98:
   ...
   case 80 : { /* you get an A+ */ break; }
   case 79 :
   case 78 : 
   ...
   case 70 : { /* you get a A */ break: }
etc.

This is ugly, but it isa switch statement. A cleaner way to use the switch statement could be to "force" avg to a discrete value, instead of a range.

这很丑陋,但它一个 switch 语句。使用 switch 语句的一种更简洁的方法可能是将 avg “强制”为离散值,而不是范围。

int percentile = avg / 10;  // integer division. 

Now range is going to be between 0 and 10, assuming avg is between 0 and 100. This will make for a slightly cleaner switch:

现在 range 将在 0 到 10 之间,假设 avg 在 0 到 100 之间。这将使开关稍微干净一点:

switch (percentile) { 
   case 10 :
   case 9:
   case 8: /* You get an A+ */ break;
   case 7: /* You get an A */ break;
   case 6: /* You get a B+ */ break;

etc.

Hope this is helpful.

希望这是有帮助的。

回答by Tejendra

The Code is always going in your default statment , as your switch statment will not be getting any input as provided in case.

代码始终在您的默认 statment 中,因为您的 switch 语句将不会获得任何输入,以防万一。

回答by SingerOfTheFall

You are using switch a little wrong, it's not the ifproblem. This:

您使用的开关有点错误,这不是if问题。这个:

switch (avg){
    case 1:{
        if ((avg >= 80) && (avg <= 100))
        {
            cout << " Your Average is: " << avg << endl;
            cout << "You Grade is A+ " << endl;
        }
        break;

means the same as

意思是一样的

if( avg == 1 )
{
    if ((avg >= 80) && (avg <= 100))
    {
        cout << " Your Average is: " << avg << endl;
        cout << "You Grade is A+ " << endl;
    }
}

So obviously the condition will never be met. For your particular case, you can just remove the switch and leave just the ifs.

所以显然条件永远不会满足。对于您的特定情况,您可以移除开关并只留下ifs。

回答by user1463509

Remove Switch- caseand you will get your desired output, as in this case it is going in default always.

删除Switch- case,您将获得所需的输出,因为在这种情况下,它始终处于默认状态。

回答by Jeeva

When you say

当你说

Switch(avg)

{
   case 1:
   break;
}

it is same as saying if(avg == 1). So remove your switch case and handle it like this

这和说的一样if(avg == 1)。所以取下你的开关盒并像这样处理它

if ((avg >= 80) && (avg <= 100))
//do this
else if ((avg >= 70) && (avg <= 79))
//do that

回答by antonio

The case situations like 1, 2, 3 are recognized as the value of avg, by the switch statement.

像 1、2、3 这样的 case 情况被 switch 语句识别为 avg 的值。

You can only use the switch() control with certain values, NOT intervals. I recommend you to use else if{} structure in this case.

您只能使用具有特定值的 switch() 控件,而不是间隔。在这种情况下,我建议您使用 else if{} 结构。

Or u can implement 1 statement in multiple cases (but wont be readable).

或者你可以在多种情况下实现 1 条语句(但不可读)。

switch(avg){
   case 80: case 81: case 82:   //do this until 100

      cout << " Your Average is: " << avg << endl;
      cout << "You Grade is A+ " << endl;
      break;
}

And you dont need to use scopes (curly brackets) for each case.

并且您不需要为每种情况使用范围(大括号)。

回答by user1529058

The best and probably the easiest thing to do is get rid of the switch statement and use "if" and "elseif".

最好也可能是最简单的方法是去掉 switch 语句并使用“if”和“elseif”。