目录
1、for 循环
# include <iostream>
int main()
{
for (int a = 0; a < 5; a++)
{
std::cout << "Hello World!" << std::endl;
}
std::cin.get();
}
这是一个简单版的for循环,而对于该循环是什么运行的,我的理解如下:
for (part1; part2; part3) // for 循环公式
// part1: 定义一个变量及数据大小;
// part2: 判断循环体的条件,若为真,则运行循环体的代码;反之,退出;
// part3: 当在part2中循环体代码运行到 “ } ”时,就执行part3代码,然后再回到part2;
即,第一部分再进行循环时执行一次,第二部分为bool值或者比较,在每一次循环前都会进行检验,第三部分为每次循环后执行的代码。所以,for循环的写法可以很随意,例如:
# include <iostream>
int main()
{
int a = 0;
for (; a < 5; a++)
{
std::cout << "Hello World!" << std::endl;
}
std::cin.get();
}
==============================================
# include <iostream>
int main()
{
int a = 0;
for (; a < 5; )
{
std::cout << "Hello World!" << std::endl;
a++;
}
std::cin.get();
}
=================================================
# include <iostream>
int main()
{
int a = 0;
bool condition = true;
for (; condition; )
{
std::cout << "Hello World!" << std::endl;
a++;
if (!(a < 5))
condition = false;
}
std::cin.get();
}
2、while 循环
while 和 for 很类似,只是while只有一个判断语句,即part2
# include <iostream>
int main()
{
int a = 0;
while(a < 5)
{
std::cout << "Hello World!" << std::endl;
a++;
}
std::cin.get();
}