【问题标题】:How to use Conditions in switch case in c++?如何在 C++ 中的 switch case 中使用条件?
【发布时间】:2020-03-26 08:05:46
【问题描述】:

有什么方法可以根据条件的答案使用 switch-case 语句?

例如:如果百分比大于 90,那么使用 switch 语句,它应该打印等级 A?

【问题讨论】:

  • 不,请改用if ... else if ... else if ... else ...
  • 但是我的老师说用 switch 语句来做到这一点
  • 这里你唯一能做的就是切换一个布尔条件:switch(value > 90) { case true: ...; break; case false: ... break; }
  • 你不能在 switch 语句中做条件。你可以做case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: case 98: case 99: case 100: ...也许这就是你老师的意思?或者你可能只是有一个不称职的老师,它发生了。或者你可能只是误解了。
  • gcc 有 case ranges extension(所以没有有效/可移植的 C++)。

标签: c++ if-statement switch-statement


【解决方案1】:

你可以这样做,

#include<iostream>
#include<string>

int main()
{
int n;

std::cout<<"Enter Mark:";
std::cin>>n;

n=n>90;

switch(n)
{
case 1:
    std::cout<<"Grade A";
    break;
case 0:
    std::cout<<"Grade B";
    break;
}

return 0;
}

或者如果你有两个以上

#include<iostream>
#include<string>

// <50 is c , 50 - 90 is b, >90 is a

int main()
{
int n;

std::cout<<"Enter Mark:";
std::cin>>n;

n=(n>50?(n>90?1:2):3);

switch(n)
{
case 1:
    std::cout<<"Grade A";
    break;
case 2:
    std::cout<<"Grade B";
    break;
case 3:
    std::cout<<"Grade C";
    break;
}

return 0;
}

【讨论】:

  • 很难看出这是对if else if else的改进
  • 最好不要将int 用作布尔值
  • @john -- 这是一个改进,因为它满足问题中的要求。是的,这些要求是人为的,但这并不意味着它们可以被忽略。
【解决方案2】:
    #include <iostream>
using namespace std;
int main()
{
    double physics,chemistry,biology,computer,math,totalMarks,obtainMarks,percentage;
    char grade;
    cout<<"Enter Total Marks=";
    cin>>totalMarks;
    cout<<"Enter Marks of Physics=";
    cin>>physics;
    cout<<"Enter Marks of chemistry=";
    cin>>chemistry;
    cout<<"Enter Marks of biology=";
    cin>>biology;
    cout<<"Enter Marks of computer=";
    cin>>computer;
    cout<<"Enter Marks of Mathematics=";
    cin>>math;
    obtainMarks=physics+chemistry+biology+computer+math;
    percentage=(obtainMarks/totalMarks)*100;
    grade=percentage>=90?'A':(percentage>=80?'B':(percentage>=70?'C':(percentage>=60?'D':(percentage>=40?'E':'F'))));

    switch(grade)
    {
        case 'A' : cout<<"you have got A grade";
        break;
        case 'B': cout<<"you have got B grade";
        break;
        case 'C': cout<<"you have got C grade";
        break;
        case 'D': cout<<"you have got D grade";
        break;
        case 'E': cout<<"you have got E grade";
        break;
        case 'F': cout<<"you have got F grade";
        break;
    }
        return 0;
}

完成!

【讨论】:

  • cout &lt;&lt; "You have got " &lt;&lt; grade &lt;&lt; " grade"替换开关更简单
猜你喜欢
  • 2011-07-24
  • 1970-01-01
  • 1970-01-01
  • 2016-09-26
  • 1970-01-01
  • 1970-01-01
  • 2012-07-13
  • 1970-01-01
相关资源
最近更新 更多