在1至100 c 之间显示7个倍数的程序
Program that displays all multiples of 7 between 1 and 100 C++
如何用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
语句替换。但是我认为您对在哪里使用if
和switch/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
类型的变量时,如果您不检查所有可能的流量,您可能至少会收到编译器警告。
相关文章:
- 我怎样才能有 2 个程序并让用户选择他们想要使用的程序?
- 每次都会重建多个程序的制作文件,尽管配方"all"被标记为虚假
- fork/pipes和运行多个程序
- 为什么两个程序中的总和值在最后不同?
- 如何在codelite中运行多个程序
- Cmake:如何引用链接到多个程序的目标文件中的文件?
- Eclipse CDT:传递具有相同文件扩展名的多个程序参数
- 在两个程序中,传递指向结构的指针的行为不同
- C++中更快地执行两个程序的可能解释(使用 Python 比较)?
- 使file执行多个程序(C/C )
- 初学者:循环单链表的第一个程序
- 创建一个启动器并将信息发送到第二个程序
- 基于两个程序之间的事件触发器访问数据(内存)
- 两个程序的不同输出将一个数字转换为二进制
- 在 2 个程序 (Windows) 之间传输信息
- 这两个程序有什么不同
- C++多个程序问题(rand、转换、崩溃)
- 为什么第二个程序的输出和第一个程序不同
- 我可以允许多个程序同时从同一个文件中读取吗
- 试图学习威纳皮.制作了第一个程序,必须向我显示一个窗口.CMD显示,但没有窗口