在1至100 c 之间显示7个倍数的程序

Program that displays all multiples of 7 between 1 and 100 C++

本文关键字:7个 程序 显示 之间      更新时间:2023-10-16

如何用switch条件语句而不是if

编写此程序
#include <iostream>
using namespace std;
int main() {
  int i;
  for (i = 1; i <= 100; i++) {
    if ((i % 7 == 0) && (i > 0)) {
      cout << i << endl;
    }
  }
  return 0;
}

您要寻找的代码应该是这样的:

#include <iostream>  // this is for std::cin and std::cout (standard input and output)
using namespace std; // to shorten std::cout into cout
int main() {
    cout << "multiples of 7 lower than 100 are:" << endl;
    for ( int i=1 ; i<=100 ; i++ ) {
        switch ( i%7 ) {
            case 0:                // this case 0 is similar to if ( i%7 == 0 )
                cout << i << " ";
                break;
            default:
                break;
        }
    }
    cout << endl;
    return 0;
}

然后输出将是:

multiples of 7 lower than 100 are:
7 14 21 28 35 42 49 56 63 70 77 84 91 98

您是:

#include <iostream>
int main()
{
    for (int i = 1; i<=100; i++)
    {
        switch(i % 7)
        {
            case 0:
                std::cout << i << std::endl;
                break;
            default:
                break;
        }
    }
    return 0;
}

在线编译:http://ideone.com/uq8jue

听起来您对开关语句有些不熟悉。Switch语句就像IF-ELSE语句一样,除了它不是布尔参数。因此,从本质上讲,它问:告诉我的价值。然后,对于每种情况(可能的结果),它具有后续行动。

因此,您想问:告诉我数字的值,模量7。如果是零,则将一个添加到计数器中。如果是1,请。

因此,您的代码应具有:

的一般结构
Switch(i%7):
   Case 0{increment counter or display to std. out or store in array}
   Case 1{other action}

可以为您的情况替换if语句用switch/case语句替换。但是我认为您对在哪里使用ifswitch/case语句有一些误解。我建议您使用此陈述,因为它们在现实生活中使用。

如果要检查条件,请使用if。例如:

if (a > b){...}if (a == 7){...}if (functionReturnsTrue()){...}

当您有一组条件时,可以使用switch/case语句,并且该集合中的每个元素的逻辑不同。例如:

enum HttpMethod {
  GET,
  POST,
  PUT,
  DELETE,
};
...
void handleHttpRequest(HttpRequest req)
{
  ...
  switch(req.getHttpMethod())
  {
    case GET: handleGETRequest(req); break;
    case POST: handlePOSTRequest(req); break;
    case PUT: handlePUTRequest(req); break;
    case DELETE: handleDELETERequest(req); break;
    default: throw InvalidHttpMethod(); // in case when noone corresponds to the variable
  }
}

当然,您可以使用if语句编写相同的内容,但是switch/case语句也具有一些汇编效果。当您switch enum类型的变量时,如果您不检查所有可能的流量,您可能至少会收到编译器警告。