其他分享
首页 > 其他分享> > for和if的嵌套使用

for和if的嵌套使用

作者:互联网

  具体实操:

/*
    2021/12/20,9:04
    目的:
        测试for和if的嵌套使用。
        (题目)求1~100之间能被3整除的所有整数之和。
*/
#include<stdio.h>

int main(void)
{
    int i;
    int sum = 0;
    
    for(i=3; i<=100; ++i)
    {
        if(i%3 == 0)
            sum = sum + i;
    }
    
    printf("sum = %d\n", sum);
    
    return 0;
}
/*
    在GDB的输出结果为:
-------------------------------------------------------
sum = 1683
-------------------------------------------------------
【总结】:
printf("sum = %d\n", sum);放在if里面可以看到每一步求和
-------------------------------------------------------
    在GDB的输出结果为:
-------------------------------------------------------
sum = 3
sum = 3
sum = 3
sum = 9
sum = 9
sum = 9
sum = 18
sum = 18
sum = 18
sum = 30
sum = 30
sum = 30
sum = 45
sum = 45
sum = 45
sum = 63
sum = 63
sum = 63
sum = 84
sum = 84
sum = 84
sum = 108
sum = 108
sum = 108
sum = 135
sum = 135
sum = 135
sum = 165
sum = 165
sum = 165
sum = 198
sum = 198
sum = 198
sum = 234
sum = 234
sum = 234
sum = 273
sum = 273
sum = 273
sum = 315
sum = 315
sum = 315
sum = 360
sum = 360
sum = 360
sum = 408
sum = 408
sum = 408
sum = 459
sum = 459
sum = 459
sum = 513
sum = 513
sum = 513
sum = 570
sum = 570
sum = 570
sum = 630
sum = 630
sum = 630
sum = 693
sum = 693
sum = 693
sum = 759
sum = 759
sum = 759
sum = 828
sum = 828
sum = 828
sum = 900
sum = 900
sum = 900
sum = 975
sum = 975
sum = 975
sum = 1053
sum = 1053
sum = 1053
sum = 1134
sum = 1134
sum = 1134
sum = 1218
sum = 1218
sum = 1218
sum = 1305
sum = 1305
sum = 1305
sum = 1395
sum = 1395
sum = 1395
sum = 1488
sum = 1488
sum = 1488
sum = 1584
sum = 1584
sum = 1584
sum = 1683
sum = 1683
*/

参考程序:

标签:459,198,int,sum,-------------------------------------------------------,嵌套,使用,16
来源: https://blog.csdn.net/qq_40555264/article/details/122036596