Switches in C++
Switches in C++
我是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,依此类推,依此类推,并使用 if
, else
块:
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;
}
}
查看枚举与阶级枚举。继续前进。
相关文章:
- netcat command in c++
- Difference in displaying cv2 Mat
- C++ MFC Libraries in Travis CI
- 如何在OpenSSL中从configuration.h.in获取configuration.h
- 创建具有 new in 函数和"this is nullptr"异常的对象
- IN, OUT, INOUT Parameters
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 有人安装"IITB Simplecpp in mac"吗?
- 从 C 样式字符串中删除子字符串 "in place" 在C++代码中
- 如何修复"error: ‘_1’ was not declared in this scope"?
- Softmax Implementation in C++
- 将 out/in out 参数与 if/switch 的 init 语句一起使用
- IF-nesting in c++
- Gurobi GRBModel and GRBmodel in C++
- Tensorflow Hub in C++
- Centos7 g++ "to_string is not in a member of std"
- InitializeCriticalSectionEx Not Located In KERNEL32.Dll
- 将 lambda 表达式传递给 std::function in C++
- @CPPFLAGS@在 Makefile.in 中意味着什么?
- std::async from std::async in windows xp