while循环
while语法形式
while 语句的语法结构和 if 语句⾮常相似,但不同的是 while 是⽤来实现循环的, if 是⽆法实现循环的。
下⾯是 while 循环的语法形式:
//形式1
while ( 表达式 )语句; //形式2
//如果循环体想包含更多的语句,需要加上⼤括号
while ( 表达式 )
{ 语句1;语句2; ...
}
执⾏流程
⾸先上来就是执⾏判断表达式,表达式的值为 0 ,循环直接结束;表达式的值不为 0 ,则执⾏循环语句,语句执⾏完后再继续判断,是否进⾏下⼀次判断。
实践
题⽬:
使⽤ while 循环在屏幕上打印1~10的值
#include <iostream>
using namespace std;int main()
{int i = 1;while (i <= 10){cout << i << " ";i++;}return 0;
}
练习
反向输出一个四位数
#include <iostream>
using namespace std;char a, b, c, d;int main()
{cin >> a >> b >> c >> d;cout << d << c << b << a;return 0;
}
#include <iostream>
using namespace std;int n;int main()
{cin >> n;while (n){cout << n % 10;n /= 10;}return 0;
}
- 要想得到 n 的最低位,可以使⽤ n % 10 的运算,得到的余数就是最低位,如:1234 % 10 得到4
- 要想去掉n的最低位,找出倒数第⼆位,则使⽤ n = n / 10 操作就可以去掉最低位的,如: n=1234/10 得到 123 ,123相较于1234就去掉了最低位, 123%10 就得到倒数第⼆位 3 。
- 循环1和2两个步骤,在n变成0之前,就能到所有的位。
1234%10 = 4
1234/10 = 123
123%10 = 3
123/10 = 12
12%10 = 2
12/10 = 1
1%10 = 1
1/10 = 0
数位之和
#include <iostream>
using namespace std;int n;int main()
{int sum = 0;cin >> n;while (n){sum += n % 10;n /= 10;}cout << sum << endl;return 0;
}
小乐乐求和
#include <iostream>
using namespace std;int n;int main()
{cin >> n;int i = 1;long long sum = 0;while (i <= n){sum += i;i++;}cout << sum << endl;return 0;
}
#include <iostream>
using namespace std;long long n;int main()
{cin >> n;long long sum = 0;sum = n * (n + 1) / 2;cout << sum << endl;return 0;
}
注意数据范围,合理设置变量数据类型,1 ≤ n ≤ 10^9,那么求和的结果在int类型的变量中是⽆法保存的。
B2078 含 k 个 3 的数
#include <iostream>
using namespace std;long long m, k;int main()
{cin >> m >> k;long long i = 0;while (m){if (m % 10 == 3)i++;m /= 10;}if (i == k)cout << "YES" << endl;elsecout << "NO" << endl;return 0;
}
还是数据范围的问题,使⽤long long类型是合适的。
B2077 角谷猜想 - 洛谷
#include <iostream>
using namespace std;
#include <cstdio>long long x;int main()
{cin >> x;while (x != 1){if (x % 2 == 1){printf("%lld*3+1=%lld\n", x, x * 3 + 1);x = x * 3 + 1;}else{printf("%lld/2=%lld\n", x, x/2);x /= 2;}}cout << "End" << endl;return 0;
}
#include <iostream>
using namespace std;
int main()
{ long long n = 0; cin >> n; while (n != 1) { if (n % 2 == 1) { cout << n << "*3+1=" << n * 3 + 1 << endl; n = n * 3 + 1; } else { cout << n << "/2=" << n / 2 << endl; n /= 2; } } cout << "End" << endl; return 0;
}
B2080 计算多项式的值
#include <iostream>
using namespace std;
#include <cstdio>double x;
int n;int main()
{cin >> x >> n;double ret = 1;double tmp = 1;while (n--){tmp *= x;ret += tmp;}printf ("%.2lf\n", ret);return 0;
}