while语句反复执行一段代码,直至给定条件为假为止
例子:求1~10的十个数之和
#include <iostream> int main() { int sum = 0, val = 1; while (val <= 10) { sum += val; ++val; } std::cout << "1到10的合计:" << sum << std::endl; return 0; }
练习:50到100的整数相加
#include <iostream> int main() { int sum = 0, val = 50; while (val <= 100) { sum += val; ++val; } std::cout << "50到100的合计:" << sum << std::endl; return 0; }
练习:使用递减运算符,打印10到0之间的数
#include <iostream> int main() { int val = 10; while (val >= 0) { std::cout << val << std::endl; --val; } return 0; }
练习:提示用户输入两个整数,打印这两个整数范围内的所有整数
#include <iostream> int main() { int v1, v2; std::cout << "请输入两个整数" << std::endl; std::cin >> v1 >> v2; int maxV, minV; if (v1 >= v2) { maxV = v1; minV = v2; } else { maxV = v2; minV = v1; } while (minV <= maxV) { std::cout << minV << std::endl; ++minV; }
return 0; }
for语句重写 求1~10的十个数之和
#include <iostream> int main() { int sum = 0; for(int val=1; val <=10 ; ++val){ sum += val; } std::cout << "1到10的合计:" << sum << std::endl; return 0; }
for语句重写 练习:50到100的整数相加
#include <iostream> int main() { int sum = 0; for(int val=50; val <=100 ; ++val){ sum += val; }
std::cout << "50到100的合计:" << sum << std::endl;
return 0; }
for语句重写 练习:使用递减运算符,打印10到0之间的数
#include <iostream> int main() { for(int val=10; val >=0 ; --val){ std::cout << val << std::endl; }
return 0; }
for语句重写 练习:提示用户输入两个整数,打印这两个整数范围内的所有整数
#include <iostream> int main() { int v1, v2; std::cout << "请输入两个整数" << std::endl; std::cin >> v1 >> v2; int maxV, minV; if (v1 >= v2) { maxV = v1; minV = v2; } else { maxV = v2; minV = v1; } for(minV;minV<=maxV;++minV){ std::cout << minV << std::endl; } return 0; }