C语言编程题计算1到n的所有偶数之和

C语言中,可以通过多种方法来计算1到n的所有偶数之和。通过不同的技术手段来计算1到n的所有偶数之和,包括简单循环、数学公式、递归、while循环和do-while循环。可以根据具体需求选择合适的方法。

1、简单循环求和

#include <stdio.h>

int sumOfEvenNumbers(int n) {
    int sum = 0;
    for (int i = 2; i <= n; i += 2) {
        sum += i;
    }
    return sum;
}

int main() {
    int n = 10;
    printf("Sum of even numbers from 1 to %d is: %d\n", n, sumOfEvenNumbers(n));
    return 0;
}

2、使用数学公式

偶数的和可以通过公式计算:(2 + 4 + 6 + ... + n),即 sum = 2 + 4 + ... + 2k = 2 * (1 + 2 + ... + k) = 2 * k * (k + 1) / 2,其中 k = n / 2

#include <stdio.h>

int sumOfEvenNumbers(int n) {
    int k = n / 2;
    return k * (k + 1);
}

int main() {
    int n = 10;
    printf("Sum of even numbers from 1 to %d is: %d\n", n, sumOfEvenNumbers(n));
    return 0;
}

3、使用递归

#include <stdio.h>

int sumOfEvenNumbers(int n) {
    if (n < 2) {
        return 0;
    }
    if (n % 2 != 0) {
        n--;
    }
    return n + sumOfEvenNumbers(n - 2);
}

int main() {
    int n = 10;
    printf("Sum of even numbers from 1 to %d is: %d\n", n, sumOfEvenNumbers(n));
    return 0;
}

4、使用while循环

#include <stdio.h>

int sumOfEvenNumbers(int n) {
    int sum = 0;
    int i = 2;
    while (i <= n) {
        sum += i;
        i += 2;
    }
    return sum;
}

int main() {
    int n = 10;
    printf("Sum of even numbers from 1 to %d is: %d\n", n, sumOfEvenNumbers(n));
    return 0;
}

5、使用do-while循环

#include <stdio.h>

int sumOfEvenNumbers(int n) {
    int sum = 0;
    int i = 2;
    do {
        if (i > n) break;
        sum += i;
        i += 2;
    } while (i <= n);
    return sum;
}

int main() {
    int n = 10;
    printf("Sum of even numbers from 1 to %d is: %d\n", n, sumOfEvenNumbers(n));
    return 0;
}

推荐阅读
cjavapy编程之路首页