C++ 如何在c+中使用开关箱中的条件+;?

C++ 如何在c+中使用开关箱中的条件+;?,c++,if-statement,switch-statement,C++,If Statement,Switch Statement,有没有办法根据条件的答案使用switch case语句 例如:如果百分比大于90,则通过使用switch语句,它应该打印a级?您可以执行以下操作: #include<iostream> #include<string> int main() { int n; std::cout<<"Enter Mark:"; std::cin>>n; n=n>90; switch(n) { case 1: std::cout<<"

有没有办法根据条件的答案使用switch case语句


例如:如果百分比大于90,则通过使用switch语句,它应该打印a级?

您可以执行以下操作:

#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;
}
#包括
#包括
int main()
{
int n;
std::coutn;
n=n>90;
开关(n)
{
案例1:
std::cout
#包括
使用名称空间std;
int main()
{
物理、化学、生物、计算机、数学、总分、获得分、百分比;
煤焦品位;
couttotalMarks;
coutphysics;
包房;
服装生物学;
计算机;
库特马斯;
获得分数=物理+化学+生物+计算机+数学;
百分比=(获得分数/总分)*100;
等级=百分比>=90?'A':(百分比>=80?'B':(百分比>=70?'C':(百分比>=60?'D':(百分比>=40?'E':'F'));
道岔(坡度)
{

案例“A”:不,可以用
if…else if…else if…else…
来代替。但是我的老师说用switch语句可以做到这一点。在这里,开关唯一能做的就是切换布尔条件:
switch(value>90){case-true:…;break;case-false:…break;}
您不能在switch语句中执行条件。您可以执行以下操作:
案例90:案例91:案例92:案例93:案例94:案例95:案例96:案例97:案例98:案例99:案例100:…
也许这就是您的老师的意思?或者您可能只是有一个不称职的老师,这种情况经常发生。或者您可能只是误解了。gcc(因此没有有效的/可移植的C++).很难看出这比
if-else有什么改进如果else
最好不要对布尔值使用
int
value@john--这是一个改进,因为它满足了问题中的要求。是的,这些要求是人为的,但这并不意味着它们可以被忽略。用
cout替换开关更简单
#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;
}