当zeno遇到for循环
//zeno.c--求序列的和
#include <stdio.h>
int main(void)
{
int t_ct; //项计数
double time, power_of_2;
int limit;
printf("enter the number of terms you want:");
scanf("%d", &limit);
for (time = 0, power_of_2 = 1, t_ct=1;t_ct <=limit; t_ct++, power_of_2 *= 2.0 )
{
time += 1.0 / power_of_2;
printf("time=%f when terms =%d.\n", time, t_ct);
}
return 0;
}
下面是序列前15项的和
出口条件循环:do while
while循环和for循环都是入口条件循环,既在循环每次迭代之前检查测试条件,所以有可能根本不执行循环体中的内容。C语言还有出口条件循环(exit-condition loop),,既在循环的每次迭代之后检查测试条件,这保证了至少执行循环体中的内容一次,这种循环称为do while循环。如下:
//do_while.c--出口条件循环
#include <stdio.h>
int main(void)
{
const int secret_code = 13;
int code_entered;
do
{
printf("to enter the triskaidekaphobia therapy club,\n");
printf("please enter the secret code number:");
scanf("%d", &code_entered);
} while (code_entered != secret_code);
printf("congratulation!you are cured!\n");
return 0;
}
运行如下
如何选择循环
首先需要确定是入口条件循环还是出口条件循环。通常,入口条件循环比较多,其原因为:一是一般原则是在执行之前测试条件比较好;二是,测试放在循环的开头,程序的可读性比较高。
嵌套循环
嵌套循环是指一个循环内包含的另一个循环,,。嵌套循环常用语按行和列显示的数据,也就是说一个循环处理一行中的所有列,另一个循环处理所有的行。