(1)1/3+3/5+5/7+……+n/(n+2) //n为任意一个奇数 (2)1!+2!+3!+4!+……+n! n=20 (n为奇数) 用c语言
时间: 2024-04-15 09:21:10 浏览: 63
以下是两个用C语言实现的例子:
(1)1/3+3/5+5/7+……+n/(n+2) //n为任意一个奇数
```c
#include <stdio.h>
int main() {
int n;
float sum = 0;
printf("请输入一个奇数n:");
scanf("%d", &n);
for (int i = 1; i <= n; i += 2) {
sum += (float)i / (i + 2);
}
printf("1/3+3/5+5/7+……+n/(n+2)的和为:%f", sum);
return 0;
}
```
(2)1!+2!+3!+4!+……+n! n=20(n为奇数)
```c
#include <stdio.h>
int main() {
int n = 20;
long long sum = 0, factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
if (i % 2 == 1) {
sum += factorial;
}
}
printf("1!+2!+3!+4!+……+n!的和为:%lld", sum);
return 0;
}
```
相关问题
运用循环分支求下列两式子+(1)1/3+3/5+5/7+……+n/(n+2)++++//n为任意一个奇数+++++(2)1!+2!+3!+4!+……+n!+++n=20
以下是两个问题的答案:
1. 运用循环分支求下列式子:1/3+3/5+5/7+……+n/(n+2),其中n为任意一个奇数。
```c
#include <stdio.h>
int main() {
int n;
float sum = 0;
printf("请输入一个奇数n:");
scanf("%d", &n);
for (int i = 1; i <= n; i += 2) {
sum += (float)i / (i + 2);
}
printf("结果为:%f", sum);
return 0;
}
```
下列表达式的值。 (1)1/3+3/5+5/7+……+n/(n+2) //n为任意一个奇数 (2)1!+2!+3!+4!+……+n! n=20
引用和引用[2]中的代码都与本题无关,不提供任何帮助。
(1) 1/3+3/5+5/7+……+n/(n+2) = (1-1/3)+(3/5-1/5)+(5/7-1/7)+……+(n/(n+2)-1/(n+2)) = 1+2/5+3/7+……+n/(n+2)-n/(n+2) = 1+2/5+3/7+……+n/(n+2)-(n+1)/(n+2) = (1+2/3)+(3/5+4/7)+(5/7+6/9)+……+n/(n+2)-(n+1)/(n+2) = 2+(3/5+5/7)+(7/9+9/11)+……+n/(n+2)-(n+1)/(***/(n+1)-(n+1)/(n+2)) = 2(1-1/(n+2)) = 2n/(n+2)
(2) 1!+2!+3!+4!+……+n!,n=20
```python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n = 20
sum = 0
for i in range(1, n+1):
sum += factorial(i)
print(sum)
```
阅读全文