C ++中的switch语句 [英] Switch statement in C++
本文介绍了C ++中的switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑:
#include <iostream>
using namespace std;
int main()
{
int score;
char grade;
cout << "Enter your score: " << endl;
cin >> score;
if (score >= 90)
grade = 'a';
if (score >= 80)
grade = 'b';
if (score >= 70)
grade = 'c';
if (score >= 60)
grade = 'd';
else
grade = 'f';
cout << grade << endl;
switch (grade) {
case 'a':
cout << "Good job" << endl;
break;
case 'c':
cout << "Fair job" << endl;
break;
case 'f':
cout << "Failure" << endl;
break;
default:
cout << "invalid" << endl;
}
cin.get();
return 0;
}
为什么我应该输入大小写"a"时输入 95
时会给出默认的切换大小写?
Why is it giving my default switch case when I enter 95
when I should be getting case 'a'?
推荐答案
您错过了一堆 else
,或者以错误的顺序进行了比较.
You're missing a bunch of else
s, or doing the comparisons in the wrong order.
95大于90,但也大于80、70和60.因此,您将得到一个'd'.
95 is greater than 90, but it's also greater than 80, 70 and 60. So you'll get a 'd'.
(而且您不在交换机中处理'd'.)
(And you're not handling 'd' in your switch.)
这篇关于C ++中的switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文