for 循环嵌套 while 循环

for 循环嵌套 while 循环

把前面的例子改为在 for 循环里面嵌套 while 循环:

#include <stdio.h>

int main(void)
{
    long sum = 1L;                       /* Stores the sum of integers      */
    int j = 1;                           /* Inner loop control variable     */
    int count = 0;                       /* Number of sums to be calculated */

    /* Prompt for, and read the input count */
    printf("\n输入一个整数,要统计的数: ");
    scanf(" %d", &count);

    for(int i = 1 ; i <= count ; i++)
    {
        sum = 1L;                          /* Initialize sum for the inner loop */
        j = 1;                               /* Initialize integer to be added    */
        printf("\n1");

        /* Calculate sum of integers from 1 to i */
        while(j < i)
        {
            sum += ++j;
            printf("+%d", j);                /* Output +j - on the same line */
        }
        printf(" = %ld\n", sum);           /* Output  = sum  */
    }
    return 0;
}Code language: PHP (php)

使用 while 循环实现相同功能:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int count = 0;
    printf("请输入一个数:");
    scanf("%d",&count);

    int sum = 0;

    for(int i = 1; i <= count; i++)
    {
        sum = 1;
        int j = 1;
        printf("1");
        while(j < i)
        {
            j++;
            sum += j;
            printf("+%d", j);
        }
        printf("=%d\n", sum);
    }

    return 0;
}Code language: PHP (php)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注