首頁  >  文章  >  後端開發  >  如何在 C Switch 語句中實現基於範圍的情況?

如何在 C Switch 語句中實現基於範圍的情況?

Linda Hamilton
Linda Hamilton原創
2024-11-13 10:34:021023瀏覽

How to Implement Range-Based Cases in a C++ Switch Statement?

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:

  • GCC 4.9 and later
  • Clang 3.5.1 and later
  • Intel C/C++ Compiler 13.0.1

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn