Java编写方法double<underline>sum<+/underline>S(int+n),计算以下公式的值s,并返回。...
时间: 2024-01-26 15:13:26 浏览: 35
以下是Java编写方法`double sumS(int n)`计算公式值s并返回的示例代码:
```java
public class Main {
public static void main(String[] args) {
int n = 5;
double result = sumS(n);
System.out.println("Result: " + result);
}
public static double sumS(int n) {
double s = 0;
for (int i = 1; i <= n; i++) {
s += (double) i / (i + n);
}
return s;
}
}
```
运行结果为:
```
Result: 1.0833333333333333
```
相关问题
Java编程1+1/2+1/3+……+1/n程序
这是一个Java编程题,要求计算1/2+1/3+1/4+1/5+……1/n的和,其中n>0。以下是程序的核心代码:
```
double sum=0;
for (int i = 0; i < n ; i++) {
sum=sum+1.0/(i+2);
}
System.out.printf("求和结果为:%.3f",sum);
```
程序中使用了for循环来计算和的值,需要注意的是,循环变量i的初始值为0,循环条件为i<n,每次循环i的值加1,计算和的公式为sum=sum+1.0/(i+2)。最后使用printf方法输出结果,保留三位小数。如果输入的n值不合法,程序会提示重新输入。
c语言设计s=1+1/2+1/3+…+1/n
以下是两种C语言设计s=1+1/2+1/3+…+1/n的例子:
1.使用for循环计算
```c
#include <stdio.h>
int main(void) {
int n = 0;
float sum = 1;
printf("请输入n: ");
scanf("%d", &n);
for (int i = 2; i <= n; i++) {
sum += 1.0 / i;
}
printf("1+1/2+1/3+...+1/%d=%f\n", n, sum);
return 0;
}
```
2.使用函数计算
```c
#include <stdio.h>
#include <stdlib.h>
int fac(int n) //阶乘函数
{
int i = 0;
int y = 1; //用来存返回值
if (0 == n || 1 == n) {
return 1;
} else {
for (i = 2; i <= n; i++) {
y *= i;
}
return y;
}
}
double sum(int n) //求和函数
{
int i = 0; //循环变量
double sum = 0; //和
for (i = 1; i <= n; i++) {
sum += 1.0 / fac(i);
}
return sum;
}
int main() {
int n = 0;
printf("请输入n: ");
scanf("%d", &n);
printf("sum = %lf\n", sum(n));
system("pause"); return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)