视频地址: https://www.bilibili.com/video/av73222285
什么是循环
在编程中,某些解决方案可能具有规律性的重复操作。比如,算自然数1至5的总和。
1
+
2
+
3
+
4
+
5
=
15
1+2+3+4+5 = 15
1+2+3+4+5=15
如果手算,我们可能会利用等差数列求和公式:
S
5
=
(
1
+
5
)
×
5
2
=
15
S_5 = \frac{(1+5)\times 5}{2} = 15
S5=2(1+5)×5=15
如果使用C语言编程,因为计算机的计算速度很快,我们可能不在意直接将每一项相加求结果:
#include <stdio.h>
int main(int argc, char* argv[])
{
int nSum = 0;
nSum += 1;
nSum += 2;
nSum += 3;
nSum += 4;
nSum += 5;
return 0;
}
但是,如果需要相加的项数变多,以上方法所写的代码就会变得复杂。为了解决这个问题,C语言中发明了循环语句。
C语言中有while、for、do…while三种循环语句。我们这次课介绍while循环。
while循环
while循环的基本语法:
while(条件表达式)
{
条件表达式成立时要执行的循环体
}
恒真条件的循环:
#include <stdio.h>
int main(int argc, char* argv[])
{
int nSum = 0;
while (1)
{
printf("循环体\r\n");
}
return 0;
}
恒假条件的循环:
#include <stdio.h>
int main(int argc, char* argv[])
{
int nSum = 0;
while (0)
{
printf("循环体\r\n");
}
return 0;
}
使用循环打印1到5
以上的示例中,循环体的执行结果是完全一样的,这在实际情况中不多见,一般循环体的运行结果,是遵循统一规律下的略作变化。
比如,我们打印数字1到5。
#include <stdio.h>
int main(int argc, char* argv[])
{
int i = 1;
while (i <= 5)
{
printf("当前数字是:%d\r\n", i);
i++;
}
return 0;
}
使用循环计算自然数前n项和
将以上代码稍作修改,可以得出计算前5项和的代码:
#include <stdio.h>
int main(int argc, char* argv[])
{
int i = 1;
int nSum = 0;
while (i <= 5)
{
printf("当前数字是:%d\r\n", i);
nSum += i;
i++;
}
printf("和为:%d\r\n", nSum);
return 0;
}
进一步修改,可以变为求任意前N项和:
#include <stdio.h>
int main(int argc, char* argv[])
{
int i = 1;
int nSum = 0;
int nCount = 0;
printf("所求项数\r\n");
scanf("%d", &nCount);
while (i <= nCount)
{
nSum += i;
i++;
}
printf("和为:%d\r\n", nSum);
return 0;
}
本文介绍了编程中的循环概念,特别是C语言中的while循环。通过实例展示了如何使用while循环打印1到5的数字以及计算自然数前n项和。文章详细解释了while循环的语法,并给出了不同情况下的应用示例。
727

被折叠的 条评论
为什么被折叠?



