for()循环以及逗号表达式注意事项

for()循环:for(; ;)

第一个表达式不必初始化一个变量,同时,它也可以是某种类型的printf()语句,要记住第一个表达式只在执行循环的其他部分之前被求值或执行一次。

举个例子:

#include<stdio.h>

int main()
{
    int n = 1;
    for(printf("welcome to hello world\n");n != 8;)
        scanf("%d",&n);
    printf("that is i wanted\n");


    return 0;
}

执行结果为:

welcome to hello world
1
3
5
66
8
that is i wanted

 

 

逗号表达式注意:

逗号运算符,优先级别最低,把两个表达式链接为一个表达式,并保证左边的表达式最先计算,它通常被用在for循环的控制表达式中,以包含多个信息,整个表达式的值为最后一个表达式的值。

例如:i = (10,20); i最后的值为20.

作为顺序点的逗号保证左边子表达式的副作用在计算右边子表达式之前生效。

测试代码如下:

#include<stdio.h>


int main()
{
    int first = 37;
    int second = 23;
    double cost = 0;
    int count = 0;
    for(count = 1,cost = first;count <= 10;++count,cost += second)
    {
        printf("count  %d, cost is $%0.2f\n",count,cost / 100.0);
    }

    
    return 0;
}

结果如下:

count  1, cost is $0.37
count  2, cost is $0.60
count  3, cost is $0.83
count  4, cost is $1.06
count  5, cost is $1.29
count  6, cost is $1.52
count  7, cost is $1.75
count  8, cost is $1.98
count  9, cost is $2.21
count  10, cost is $2.44

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值