C07-3.30循环2
原题链接:38471.note12025-03-30 20:03:16
发布于:江苏
一、作业回顾
T1 阶乘
阶乘的常规操作,可以对照累加求和进行理解和实现。
#include <iostream>
using namespace std;
int main() {
int n;
int sum = 1;
cin >> n;
for (int i= 1; i<=n; ++i) {
sum *= i; //累乘的结果
}
cout << sum;
return 0;
}
T2 偶数输出
升序和降序的实现,注意要判断偶数的情况。
#include<iostream>
using namespace std;
int main()
{
int x, y;
cin >> x >> y;
if(x > y) {
for(int i = x; i >= y; i--) {
if(i % 2 == 0) {
cout << i << " ";
}
}
} else {
for(int j = x; j <= y; j++) {
if(j % 2 == 0) {
cout << j << " ";
}
}
}
return 0;
}
二、while 与 do while
while单词的意思就是“当...的时候”, 在循环中表示的就是当前条件满足的时候执行循环体。
while (){
}
do {
} while();
循环输出的结果
int i=1;
while (i<=10){
cout << ++i <<' '; //2 ~ 11, 注意这里的++i是先加再进行输出, 最后的10也会+1之后输出。
}
int i = 10;
do {
cout << i <<endl;
}while (i<8); //先做。即使条件不成立也会输出一次
int i = 10;
while (i < 8){
cout << i << endl;
} //先判断。条件成立再输出
三、课堂练习
实例1: 如意金箍棒1
注意循环的条件,只要金箍棒的长度小于目标长度,那么就继续的*2。
#include<iostream>
using namespace std;
int main(){
int n, w, k=0;
cin >> n >> w;
while (n < w){
//将金箍棒的长度 * 2
n *= 2;
k++;
}
cout << k;
return 0;
}
其实也可以转成for循环来实现,参考程序如下。
//任何的while循环都可以转换为for循环
for( ; n<w; k++){
n*=2;
}
cout<<k;
实例2:数位拆分
while循环+%运算的经典使用。
#include<iostream>
using namespace std;
int main(){
int n;
cin >> n;
while (n)
{
cout << n%10 << endl; //取出最后一位
n /= 10; //消除最后一位
}
return 0;
}
for循环实现:
for (; n; n/=10){
cout << n%10<< endl;
}
实例3:数位求和
#include <iostream>
using namespace std;
int main() {
int n, sum = 0;
cin >> n;
while(n != 0) {
sum += n % 10;
n /= 10;
}
cout << sum;
return 0;
}
实例4:小玉游泳
#include <iostream>
using namespace std;
int main(){
int cnt = 0;
double x, n = 2;
cin >> x;
while (x>0){
x -= n;
//下次移动的是上次距离的98%
n *= 0.98;
cnt ++ ;
}
cout << cnt;
return 0;
}
四、作业提示
如意金箍棒II 思路提示
cin>>n>>w; //n表示初始长度, w表示目标长度
//参考如意金箍棒I,只要金箍棒的长度大于目标长度,那么就继续的除以2。
//需要结合题目的样例解释,理解下如果等于目标长度还要不要除以2。
while (n > w){
n/=2;
k++;
}
这里空空如也
有帮助,赞一个