如何将switch语句转换为c ++的if语句

时间:2017-09-29 18:38:49

标签: c++

#include<iostream>

using namespace std;

int main()
{
    float a, b, c, s, r, area;
    int ch;
    cout << "1.Area Of Circle";
    cout << "2.Area Of Rectangle";
    cout << "3.Area Of Triangle";
    cout << "Enter Your Choice:";
    cin >> ch;
    switch (ch)
    {
        case 1:
        {
            cout << "Enter Radius Of The Circle: ";
            cin >> r;
            area = 3.14 * r * r;
            break;
        }
        case 2:
        {
            cout << "Enter Length and Breadth Of Rectangle:";
            cin >> a >> b;
            area = a * b;
            break;
        }
        case 3:
        {
            cout << "Enter Three Sides Of The Triangle:";
            cin >> a >> b >> c;
            s = (a + b + c) / 2;
            area = sqrt(s * (s - a) * (s - b) * (s - c));
            break;
        }
        default:
            cout << " Invalid Choice Try Again...!!!";
            break;
    }
    cout << "Area = " << area << endl;
    return 0;
}

1 个答案:

答案 0 :(得分:1)

所以像这样,

#include <iostream>
int x;

std::cin >> x;

switch(x) {
  case 1:
      // do things here
      break;
  case 2:
      // other things
      break;
  default:
     //when nothing matches

}

会变成

#include <iostream>
int x;

std::cin >> x;

if(x == 1) {
   //do things
}
else if(x == 2) {
  // other things
}
else {
  // when nothing matches
}