for:for循环重点是是达到指定次数。
while:while循环重点是满足条件即停止循环。
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
int n;
int maxn = 0, minn = 200, sum = 0;//minn只要设置成比100大的数即可。
cin >> n;
while(n)//n==0为false,停止while循环
{
if(n > maxn) maxn = n;//更新最大值
if(n < minn) minn = n;//更新最小值
sum += n;
cin >> n;
}
cout << maxn << " " << minn << " " << sum << endl;
return 0;
}
#include<iostream>
#include<cstdio>
//#define EPS 0.001
double EPS = 0.001;
using namespace std;
int main()
{
double a;
cin >> a;
if(a >= 0)
{
double x1 = a/2, lastx = x1 + 1 + EPS;//lastx表示前一次的x,只要比x1大EPS即可 初始数据
while ((x1 - lastx) > EPS || (lastx - x1) > EPS)//绝对值小于EPS终止循环 迭代条件
{
lastx = x1;
x1 = (x1 + a/x1) / 2;
}
cout << x1 << endl;
}
else
cout << "It's can't be nagitive." << endl;
return 0;
}
【迭代公式写代码】
第一步: 先写初始的迭代数据;
第二步: 用while循环进行迭代。
【重点】语句组至少要执行一次。
#include<iostream>
using namespace std;
int main()
{
int n = 1;
do
{
cout << n << " ";
n *= 2;
} while (n < 10000);
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int n = 1;
while (n < 10000)
{
cout << n << " ";
n *= 2;
}
return 0;
}