简体   繁体   中英

How to use Conditions in switch case in c++?

Is there any way I can use a switch-case statement based on the answer of condition?

For example: if a percentage is greater than 90 then by using the switch statement, it should print grade A?

You can do something like,

#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;
}

or if you have more than two

#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;
}
    #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;
}

done!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM