生成1,1/3,1/5,1/7……的数列
时间: 2024-09-29 20:04:20 浏览: 30
要生成序列1, 1/3, 1/5, 1/7, ..., 可以创建一个循环,每次迭代计算下一个奇数倒数并添加到结果中。这里是一个C#示例[^1]:
```csharp
using System;
double SumOfOddInverses(int n)
{
double sum = 1.0;
for (int i = 1; i <= n; i += 2)
{
// 计算奇数项的倒数
sum += 1.0 / i;
}
return sum;
}
// 调用函数生成1到某个n范围内的序列
double result = SumOfOddInverses(100);
Console.WriteLine($"Sum of odd reciprocals up to 1/{100} is: {result}");
```
同样,在C语言中,可以使用相似的方法[^2]:
```c
#include <stdio.h>
double sum_of_odd_reciprocals(int n) {
double sum = 1.0;
for (int i = 1; i <= n; i += 2) {
sum += 1.0 / i;
}
return sum;
}
int main() {
int n = 200;
double result = sum_of_odd_reciprocals(n);
printf("The sum of odd reciprocals from 1 to %d is: %.10f\n", n, result);
return 0;
}
```
阅读全文