c++ - 为什么答案不显示

标签 c++

我正在学习 C++,老实说,我是新手,会犯基本错误。 我已经开始编写代码来显示输入的数字是否可以被 2、4、5、8、10 整除最多 5 次

问题是它不显示答案...

#include <iostream>
using namespace std;
int main() {
    int num;

    cout << "type in number to check if number is divisible by 2, 4, 5, 8, 10" << endl;
    cin >> num;
    switch (num) {
    case 1:
        if (num / 2 == 0) {
            cout << num << "is divisble by 2" << endl;
        }
    case  2:
        if (num / 4 == 0) {
            cout << num << "is divisible by 4" << endl;
        }
    case  3:
        if (num / 5 == 0) {
            cout << num << "is divisible by 5" << endl;
        }
    case  4:
        if (num / 8 == 0) {
            cout << num << "is divisible by 8" << endl;
        }
    case  5:
        if (num / 10 == 0) {
            cout << num << "is divisible by 10" << endl;
        }
        num++;
        if (num == 5) break;
    }
    return 0;
}

最佳答案

你对switch语句的理解不对。

switch(num) {

    case 1 :
      // This block will be executed only when num is equal to 1.
      if (num/2 == 0)  {
        cout<<num<<"is divisble by 2"<<endl;}

对于您的问题,您只需要一系列 if 语句。

cin >>num;

if (num % 2 == 0)  {  // Not  if ( num/2 == 0)
   cout<<num<<"is divisble by 2"<<endl;
}

if (num % 4 == 0){
   cout<<num<<"is divisible by 4"<<endl;
}

if (num % 5 == 0) {
      cout<<num<<"is divisible by 5"<<endl;
}

if (num % 8 == 0){
         cout<<num<<"is divisible by 8"<<endl;
} 

if (num % 10 == 0)
{
   cout<<num<<"is divisible by 10"<<endl;
} 

关于c++ - 为什么答案不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56028782/

相关文章:

c++ - 复制具有多态内容的 std::unique_ptr 的 std::map

c++ - 在不使用任何循环的情况下动态分配二维数组?

c++ - 如何在我的 iPhone 应用程序中使用 C++ STL 容器?

c++ - 使用 const char 出错

c++ - 编译 Boost segment_utils.hpp 时出错

c# - 转换 C++ 中的 std::string,使其成为 C# 中的 byte[]

命名空间的 C++ 继承问题

c++ - 如何删除C++中给定矩阵中的特定行和列?

c++ - 类不能包含内部定义枚举的运算符函数?

c++ - 平衡括号问题为什么检查它是否为空?