for(起始表达式;条件表达式;末尾循环体) { 循环语句; }

 

可以拆分为:

 

 

注意:for循环中的表达式,要用分号进行分隔

总结:while , do…while, for都是开发中常用的循环语句,for循环结构比较清晰,比较常用

敲桌子案例 :从1开始数到数字100, 如果数字个位含有7,或者数字十位含有7,或者该数字是7的倍数,我们打印敲桌子,其余数字直接打印输出。

 1 #include <iostream>
 2 using namespace std;
 3 int main()
 4 {
 5     for (int i = 1; i < 101; i++)
 6     {
 7         if (i / 10 == 7 || i % 10 == 7 || i % 7 == 0)
 8         {
 9             cout << "敲桌子" << endl;
10         }
11         else 
12             cout << i << endl;
13     }
14     return 0;
15 }

 

 1 #include<iostream>
 2 using namespace std;
 3 int main() {
 4     for (int a = 1; a <= 100; a++)
 5     {
 6         if (a % 7 == 0)
 7         {
 8             cout << "敲桌子" << endl;
 9         }
10         else if (a % 10 == 7)
11         {
12             
13             
14                 cout << "敲桌子" << endl;
15             
16         }
17         else if (a / 10 % 10 == 7)
18         {
19             cout << "敲桌子" << endl;
20         }
21         else
22             cout << a << endl;
23     }
24     return 0;
25 }

 

 

 

posted on 2022-07-21 15:44  在野武将  阅读(62)  评论(0)    收藏  举报