#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
int main(void) {
int s;
int p;
s = 1;
p = 0;
//直接先循环一次
do {
//从1加到100 并赋值给p
p += s;
++s;
}
while (s <= 100); // s循环到100
//打印并输出结果
cout << "p=" << p << endl;
system("pause");
return 0;
}
//1+2+3+4+...100
第3节"不服就干-直接干"之do-while循环
使用场合:
先执行一次循环体,然后再判断条件,以判定是否继续下一轮循环!
即:至少执行一次循环体!
使用方法
do {
循环体
} while (条件)
使用do-while计算 1+2+3+…100
#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
int main(void) {
int s = 0;
int i = 1;
do {
s += i;
i++;
} while(i<=100);
cout << s << endl;
system("pause");
return 0;
}
特殊用法:【在特殊的宏定义中使用】
do {
// 循环体
} while(0);