C语言实现
在C语言中,我们可以直接通过迭代计算每一项的分子和分母,并累加它们的和(注意这里累加的是每一项的数值,即分数转换为浮点数后的值)。这里给出两种实现方式:
方法1:直接计算并累加
c复制代码 #include <stdio.h> int main() { double sum = 0.0; int numerator = 2, denominator = 1; for (int i = 0; i < 20; i++) { sum += (double)numerator / denominator; int nextNumerator = numerator + denominator; denominator = numerator; numerator = nextNumerator; } printf("The sum of the first 20 terms is: %.15f\n", sum); return 0; }
方法2:使用结构体和函数封装
如果你想要更结构化的代码,可以使用结构体来存储分数,并定义函数来计算下一项和累加和。
c复制代码 #include <stdio.h> typedef struct { int numerator; int denominator; } Fraction; Fraction getNextFraction(Fraction f) { Fraction next; next.numerator = f.numerator + f.denominator; next.denominator = f.numerator; return next; } double sumFractions(int n) { double sum = 0.0; Fraction f = {2, 1}; for (int i = 0; i < n; i++) { sum += (double)f.numerator / f.denominator; f = getNextFraction(f); } return sum; } int main() { printf("The sum of the first 20 terms is: %.15f\n", sumFractions(20)); return 0; }
Python实现
Python的实现通常更加简洁和直观。
方法1:直接计算并累加
python复制代码 def sum_fractions(n): numerator, denominator = 2, 1 total_sum = 0.0 for _ in range(n): total_sum += numerator / denominator numerator, denominator = numerator + denominator, numerator return total_sum print(f"The sum of the first 20 terms is: {sum_fractions(20)}")
方法2:使用生成器
如果你想要一个更“Pythonic”的解决方案,可以使用生成器来生成分数序列,并计算它们的和。
python复制代码 def fraction_generator(n): numerator, denominator = 2, 1 for _ in range(n): yield numerator / denominator numerator, denominator = numerator + denominator, numerator def sum_fractions(n): return sum(fraction_generator(n)) print(f"The sum of the first 20 terms is: {sum_fractions(20)}")
这两种Python方法都简洁地实现了题目要求,并展示了Python在处理此类问题时的灵活性和强大功能。