while的語法只有一種,卻能變化出無窮無盡的用法。
其中最常見的用途就是產生數列了。
例如:
1 3 5 7 9 11 13 15 17 19
10 9 8 7 6 5 4 3 2 1 0
3 9 27 81 243 729 2187
A. 給變數i初始值
while( B. 變數i的邊界條件 )
{
利用變數i做一些事情...
C. 改變變數i
}
1 3 5 7 9 11 13 15 17 19
#include<iostream>
using namespace std;
int main()
{
int i;
i = 1; //A
while( i<=19 ) //B
{
cout << i << " ";
i = i+2; //C
}
return 0;
}
利用while輸出以下的數列吧!
1 2 3 4 5 6 7 8 9 10
1 3 5 7 9 11 13 15 17 19
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30
10 9 8 7 6 5 4 3 2 1 0
2 4 8 16 32 64 128 256 512
3 9 27 81 243 729 2187
-100 -90 -80 -70 -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
128 64 32 16 8 4 2 1
1 2 3 4 5 6 7 8 9 10
#include<iostream>
using namespace std;
int main()
{
int i;
i = 1;
while( i<=10 )
{
cout << i << " ";
i = i+1;
}
return 0;
}
1 3 5 7 9 11 13 15 17 19
#include<iostream>
using namespace std;
int main()
{
int i;
i = 1;
while( i<=19 )
{
cout << i << " ";
i = i+2;
}
return 0;
}
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30
#include<iostream>
using namespace std;
int main()
{
int i;
i = 2;
while( i<=30 )
{
cout << i << " ";
i = i+2;
}
return 0;
}
10 9 8 7 6 5 4 3 2 1 0
#include<iostream>
using namespace std;
int main()
{
int i;
i = 10;
while( i>=0 )
{
cout << i << " ";
i = i-1;
}
return 0;
}
2 4 8 16 32 64 128 256 512
#include<iostream>
using namespace std;
int main()
{
int i;
i = 2;
while( i<=512 )
{
cout << i << " ";
i = i*2;
}
return 0;
}
3 9 27 81 243 729 2187
#include<iostream>
using namespace std;
int main()
{
int i;
i = 3;
while( i<=2187 )
{
cout << i << " ";
i = i*3;
}
return 0;
}
-100 -90 -80 -70 -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100
#include<iostream>
using namespace std;
int main()
{
int i;
i = -100;
while( i<=100 )
{
cout << i << " ";
i = i+10;
}
return 0;
}
128 64 32 16 8 4 2 1
#include<iostream>
using namespace std;
int main()
{
int i;
i = 128;
while( i>=1 )
{
cout << i << " ";
i = i/2;
}
return 0;
}