用C ++开关

时间:2016-06-14 14:52:30

标签: c++

我是C ++和编程的新手,并试图想出一种在C ++中创建一个开关的方法,当输入的数字可以被3,5和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;
    }

}

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

3 个答案:

答案 0 :(得分:9)

在C ++中,switch标签必须是编译时可评估的常量表达式,它们是整数类型。

例如,

“/ 3”是字符串文字,因此不符合该要求。

在这种情况下,使用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*/
}

答案 1 :(得分:1)

您可以使用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<<"Buzz\n";
else   // neither
       cout<<"......"<<'\n';
顺便说一句,你必须阅读关于C ++的基础书

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

的更多信息

答案 2 :(得分:0)

如果你真的想用switch,这是一个方法,但不是很好。最简单的方法是Bathsheba如何说。

#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;
   }

}

查看enum vs class enum的内容。继续。