c语言4-13 求1到n的和

 

1、while语句

#include <stdio.h>

int main(void)
{
    int i, sum = 0;
    puts("please input an integer.");
    do
    {
        printf("i = "); scanf("%d", &i);
        if (i <= 0)
            puts("the range of i is: > 0. ");
    }
    while (i <= 0);
    
    printf("the sum of 1 to %d is: ", i);
    while (i > 0)
    {
        sum += i;
        i--;
    }
    
    printf("%d\n", sum);
    return 0;
}

 

2、while语句;

#include <stdio.h>

int main(void)
{
    int i = 1, j, sum = 0;
    puts("please input an integer.");
    do
    {
        printf("j = "); scanf("%d", &j);
        if (j <= 0)
            puts("the range of j is: > 0 ");
    }
    while (j <= 0);
    
    printf("the sum of 1 to %d is: ", j);
    while (i <= j)
    {
        sum += i;
        i++;
    }
    printf("%d\n", sum);
    
    return 0;
}

 

3、for语句

#include <stdio.h>

int main(void)
{
    int i, sum = 0;
    puts("please input an integer.");
    do
    {
        printf("i = "); scanf("%d", &i);
        if (i <= 0)
            puts("the range of i is : > 0 ");
    }
    while (i <= 0 );
    
    printf("the sum of 1 to %d is: ", i);
    for (i; i > 0; i--)
    {
        sum += i;
    } 
    printf("%d\n", sum );
    
    return 0;
}

 

4、for语句

#include <stdio.h>

int main(void)
{
    int i, j, sum = 0;
    puts("please input an integer.");
    do
    {
        printf("j = "); scanf("%d", &j);
        if (j <= 0)
            puts("the range of j is: > 0. ");
    } 
    while (j <= 0);
    
    printf("the sum of 1 to %d is: ", j);
    for (i = 1; i <= j; i++)
    {
        sum += i;
    }
    printf("%d\n", sum);
    
    return 0;
}

 

5、do语句

#include <stdio.h>

int main(void)
{
    int i, sum = 0;
    puts("please input an integer.");
    do
    {
        printf("i = "); scanf("%d", &i);
        if (i <= 0)
            puts("the range of i is: > 0 ");
    }
    while (i <= 0);
    
    printf("the sum of 1 to %d is: ", i);
    do
    {
        sum += i;
        i--;
    }
    while (i > 0);
    printf("%d\n", sum);
    
    return 0;
}

 

6、do语句

#include <stdio.h>

int main(void)
{
    int i = 1, j, sum = 0;
    puts("please input an integer.");
    do
    {
        printf("j = "); scanf("%d", &j);
        if (j <= 0)
            puts("the range of j is: > 0 ");
    }
    while (j <= 0);
    
    printf("the sum of 1 to %d is: ", j);
    do
    {
        sum += i;
        i++;
    }
    while (i <= j);
    printf("%d\n", sum);
    
    return 0; 
}

 

posted @ 2021-04-19 18:37  小鲨鱼2018  阅读(1051)  评论(0编辑  收藏  举报