续C控制语言:循环

当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;

}

运行如下

如何选择循环 

首先需要确定是入口条件循环还是出口条件循环。通常,入口条件循环比较多,其原因为:一是一般原则是在执行之前测试条件比较好;二是,测试放在循环的开头,程序的可读性比较高。

嵌套循环

嵌套循环是指一个循环内包含的另一个循环,,。嵌套循环常用语按行和列显示的数据,也就是说一个循环处理一行中的所有列,另一个循环处理所有的行。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值