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; }