使用开关语句 C++ 检查您的评分
check you grade using switch statements c++
实际上,我不知道从哪里开始。当我在课堂上进行测验时,我遇到了这个问题,我必须弄清楚用户何时输入一些年龄,结果将显示该数字是老、年轻还是婴儿。我已经知道并且这不适用于"开关语句",并且很难写"案例 0:......案例100:"。因为我用谷歌搜索了这个问题,但只能使用"if/else 语句"。如果有任何示例代码与"开关语句"一起使用,或者只是说继续使用"if/else 语句",请指导我。
亲切的问候
这里的开关语句效果很好。
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
int age;
cout << "Enter your age: " << endl;
cin >> age;
switch (age) {
case 0:
cout << "Young" << endl;
break;
case 20:
cout << "Middle" << endl;
break;
case 70:
cout << "Prime" << endl;
break;
default:
cout << "Invalid age" << endl;
}
cout << "Your age is " << age << endl;
system("pause");
return 0;
}
在这里 if/else 语句并且效果很好
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
int age;
cout << "Enter your age: " << endl;
cin >> age;
if (age >= 50) {
cout << "Prime" << endl;//
}
else if (age >= 20) {
cout << "Middle" << endl;//
}
else if (age >= 10) {
cout << "Young" << endl;//
}
else {
cout << "Baby" << endl;//
}
system("pause");
return 0;
}
为什么要使用 switch
来表示如果写成if
块会更好的东西?
一些编译器允许基于范围的switch
作为语言扩展(使用像 case 20...69:
这样的符号,但在我看来这毫无意义,因为您最终得到的只是不可移植的代码。
始终为工作选择正确的工具:您不会把衣服放在洗碗机里吧?
参考资料:https://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html
参考 c++ 文档:
switch 语句的语法有点奇特。其目的是在众多可能的常量表达式中检查一个值。它类似于连接 if-else 语句,但仅限于常量表达式。
不能对表达式使用通配符语法。在我发现的一段类似的代码中,首先评估用户输入并分配了一个从 a 到 d 的字母。在开关的情况下,该字母给出了特定的输入。
您可以像这样堆叠交换机条件:
#include<iostream>
using namespace std;
void Main()
{
int age; // User-input
switch (age)
{
case 0:
default:
cout << "Invalid age." << endl;
break;
case 1:
case 2:
case 3:
// Continue until last age of "young" is reached.
}
}
但是,你可以看到这将是多么可怕。
相关文章:
- valgrind-hellgrind与泄漏检查的结果不同
- C++模板来检查友元函数的存在
- 检查输入是否不是整数或数字
- 试图让变量检查数组中的某些内容
- 检查值是否在集合p1和p2中,但不在p3中
- C++概念:如何使用'concept'检查模板化结构的属性?
- 概念TS检查忽略私有访问修饰符
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- 如何在C++中检查2D数组中负值的输入验证
- C++:正在检查LinkedList中的回文-递归方法-错误
- 使用for循环检查数组中的重复项
- 如何检查一个c++字符串中有多少相同的字符/数字
- 检查不带转换的扫描格式
- 如何检查线程是否锁定
- 清除前检查矢量
- 如何处理来自核心指南检查器的关于gsl::at的静态分析警告
- C++LDAP检查用户是否是特定组的成员
- 检查TCHAR数组输入是否为带符号整数C++
- 用概念检查属性的类型