Switches in C++

Switches in C++

本文关键字:C++ in Switches      更新时间:2023-10-16

我是C 的新手,一般而言编程,并试图找出一种在C 中创建开关的方法3和5既是我到目前为止的:

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int number;
    cout << "Please input a number and then press the enter key" << endl;
    cin >> number;
    switch (number){
    case "/3":
        cout << "Fizz" << endl;
        break;
    case "/5":
        cout << "Buzz" << endl;
        break;
    case "/3" "/5":
        cout << "FizzBuzz" << endl;
        break;
    default:
        cout << "Please select another number." << endl;
    }
}

对此的任何帮助将不胜感激!:)

在C 中switch标签必须是可评估的常数表达式,这是整体类型。

例如

在这种情况下,使用 number % 3 == 0测试3,依此类推,依此类推,并使用 ifelse块:

if (number % 15 == 0){
    /*FizzBuzz - do this one first as my `if` block is not mutually exclusive*/
} else if (number % 3 == 0){
    /*Fizz*/
} else if (number % 5 == 0){
    /*Buzz*/
}

您可以使用if else

int remainder1 = 0, remainder2 = 0;
remainder1 = number % 3;
remainder2 = number % 5;
if(remainder1 == 0 && remainder2 ==0) // both
       cout<<"FizzBuzz"<<'n';
else if(remainder1 == 0)  // number can be divided by 3
       cout<<"Fizz"<<'n';
else if(remainder2 == 0) // number can be divided by 5
       cout<<"Buzzn";
else   // neither
       cout<<"......"<<'n';

顺便说一句,您必须阅读基本书关于C 。

在这里,您可以了解有关Switch

的更多信息

如果您真的想使用Switch,则是一种方法,但不是很好。最简单的方法是巴西巴说的方式。

#include <iostream>
#include <cmath>
using namespace std;
enum class divided { DivideBy3  , DivideBy5 , DivideBy3and5 }; // "strong enum" 
// enum class divided { DivideBy3  , DivideBy5 , DivideBy3and5 }; //also good but can be unsafe
divided getCase(int number)
{
  divided div;
  if(number%3 == 0)
        div = divided::DivideBy3;
  if(number%5 == 0)
        div = divided::DivideBy5;
  if(number%3 ==0 && number%5 == 0)
        div = divided::DivideBy3and5;
  return div;
}
int main()
{
  int numberIn;
  cout << "Please input a number and then press the enter key" << endl;
  cin >> numberIn;
  divided number =  getCase(numberIn);
  switch (number)
  {
  case divided::DivideBy3:
      cout << "Fizz" << endl;
    break;
  case divided::DivideBy5:
      cout << "Buzz" << endl;
    break;
  case divided::DivideBy3and5:
      cout << "FizzBuzz" << endl;
    break;
  default:
      cout << "Please select another number." << endl;
   }
}

查看枚举与阶级枚举。继续前进。