基本上没有什么差别,可以通用。所谓的for适用于循环次数已知的说法好像没什么道理。以下是baidu到的两种说法,差不多。
1.
The choice between while and for is arbitrary, based on which seems clearer. The for is usually appropriate for loops in which the initialization and increment are single statements and logically related, since it is more compact than while and it keeps the loop control statements together in one place.
至于在while与for这两个循环语句中使用哪一个,这是随意的,主要看使用哪一个更能清楚 地描述问题。for语句比较适合描述这样的循环:初值和增量都是单个语句并且是逻辑相关的, 因为for语句把循环控制语句放在一起,比while语句更紧凑。
2.
在for循环中,循环控制变量的初始化和修改都放在语句头部分,形式较简洁,且特别适用于循环次数已知的情况。在while循环中,循环控制变量的初始化一般放在while语句之前,循环控制变量的修改一般放在循环体中,形式上不如for语句简洁,但它比较适用于循环次数不易预知的情况(用某一条件控制循环)。两种形式各有优点,但它们在功能上是等价的,可以相互转换。
输出10到0的数字:
用while形式写的:
#include<iostream>
using namespace std;
int main()
{
int i=10;
while(0<=i&&i<=10)
{
cout<<i<<" ";
i--;
}
cout<<endl;
return 0;
}
用for形式写的:
#include<iostream>
using namespace std;
int main()
{
for(int i=10;0<=i;i--)
cout<<i<<" ";
cout<<endl;
return 0;
}