Selecting a Range of Values in a Switch Statement
In the example provided, the compiler encounters errors due to an invalid syntax in the switch statement. The code attempts to specify ranges of values using the syntax "case >= value" and "case == value," which is not standard in C++.
To resolve the issue, it's important to note that some compilers support case ranges as an extension to the C++ language. The syntax for specifying a range of values is "case value ... value."
Revised Code with Case Ranges:
#include <iostream> using namespace std; int main() { int score; // Get score from user cout << "Score: "; cin >> score; // Switch statement with case ranges switch (score) { case 0: cout << "a"; break; case 0 ... 9: cout << "b"; break; case 11 ... 24: cout << "c"; break; case 25 ... 49: cout << "d"; break; case 50 ... 100: cout << "e"; break; default: cout << "BAD VALUE"; break; } cout << endl; return 0; }
Compiler Support for Case Ranges:
Case ranges are not supported in all compilers. Here are some known compilers that support this feature:
If your compiler does not support case ranges, you will need to use a different approach for selecting a range of values in a switch statement. One option is to use a series of nested if-else statements as follows:
if (score >= 100) { cout << "a"; } else if (score >= 50) { cout << "b"; } else if (score >= 25) { cout << "c"; } else if (score >= 10) { cout << "d"; } else if (score > 0) { cout << "e"; } else if (score == 0) { cout << "f"; } else { cout << "BAD VALUE"; }
以上是如何在 C Switch 語句中實現基於範圍的情況?的詳細內容。更多資訊請關注PHP中文網其他相關文章!