C++第二课 while循环
循环
while(条件)
{
循环体
}
#include<bits/stdc++.h>
using namespace std;
int main(){
int i,s;
i = 1;
s = 0;
while(i <= 100)
{
s = s + i;
i = i + 1;
}
cout<<s<<endl;
return 0;
}
计算1到100的和,最后运行结果为:5050
#include<bits/stdc++.h>
using namespace std;
int main(){
int i,s;
i = 2;
s = 0;
while(i <= 1000)
{
s = s + i;
i = i + 2;
}
cout<<s<<endl;
return 0;
}
计算1到1000所有偶数的和,最后运行结果为:250500
#include<bits/stdc++.h>
using namespace std;
int main(){
int m,n,i,j;
m = 2;
n = 2;
i = (m++)%3;
j = (++n)%3;
cout<<i<<" "<<m<<endl;
cout<<j<<" "<<n<<endl;
return 0;
}
自加,m++是先运算后自加,++m是先自加再运算,运行结果:
2 3
0 3
#include<bits/stdc++.h>
using namespace std;
int main(){
int i,n,s;
i = 1;
s = 0;
cin>>n;
while(i <= n)
{
if(i%2 == 1)
{
s = i + s;
}
i++;
}
cout<<s<<endl;
return 0;
}
求1到键盘输入整数之间奇数的和
#include<bits/stdc++.h>
using namespace std;
int main(){
int m,n,s;
s = 0;
cin>>m>>n;
if(m >= 0 && m <= n && n <= 300)
{
while(m <= n)
{
if(m%2 == 1)
{
s = m + s;
}
m++;
}
}
cout<<s<<endl;
return 0;
}
求指定范围内奇数的和
#include<bits/stdc++.h>
using namespace std;
int main(){
int i,a,n,s;
i = 1;
s = 1;
cin>>a>>n;
if(-1000000 <= a && a <= 1000000 && 1 <= n && n <= 10000)
{
while(i <= n)
{
s *= a;
i++;
}
cout<<s<<endl;
}
return 0;
}
乘方计算
#include<bits/stdc++.h>
using namespace std;
int main(){
int i,j,k,s;
s = 0;
i = 1;
j = 1;
cin>>k;
if(k >= 1 && k <= 46)
{
if(k == 1 || k == 2)
{
s = 1;
}
else
{
s = i + j;
while(k >= 4)
{
i = j;
j = s;
s = i + j;
k = k - 1;
}
}
}
cout<<s<<endl;
return 0;
}
斐波那契数列