用java编写程序,计算数学e的值,e=1/1-1/2+1/3-1/4+...+/- 1/n ...怎么编写啊
答案:2 悬赏:60 手机版
解决时间 2021-11-28 02:18
- 提问者网友:贪了杯
- 2021-11-27 10:23
用java编写程序,计算数学e的值,e=1/1-1/2+1/3-1/4+...+/- 1/n ...怎么编写啊
最佳答案
- 五星知识达人网友:天凉才是好个秋
- 2021-11-27 11:52
System.out.printf("1/1-1/2+..1/%s=%.5f\n", n, 结果);
.............
private static double myseries_ans(int n) {
double res = 1;
boolean sign=true;
for (int i = 2; i<=n; i++) {
if(sign){
res=res-1D/i;
}else{
res=res+1D/i;
}
sign=!sign;
}
return res;
}
.............
private static double myseries_ans(int n) {
double res = 1;
boolean sign=true;
for (int i = 2; i<=n; i++) {
if(sign){
res=res-1D/i;
}else{
res=res+1D/i;
}
sign=!sign;
}
return res;
}
全部回答
- 1楼网友:神也偏爱
- 2021-11-27 13:17
import java.util.Scanner;
public class S1014060163 {
public static void main(String[] args) {
final Scanner scanner = new Scanner(System.in);
int value = 1;
while (value > 0) {
System.out.println("请输入一整数(0结束): ");
value = scanner.nextInt();
double result = 1.0;
final StringBuilder sb = new StringBuilder("1/1");
for (int index = 2, sign = -1; index <= value; index++, sign *= -1) {
sb.append(sign > 0 ? '+' : '-').append("1/").append(index);
result += (1.0 / (index * sign));
}
if (value != 0) {
sb.append("=").append(result);
System.out.println(sb.toString());
}
}
}
}
应该差不多了,只是不要有非法数据
public class S1014060163 {
public static void main(String[] args) {
final Scanner scanner = new Scanner(System.in);
int value = 1;
while (value > 0) {
System.out.println("请输入一整数(0结束): ");
value = scanner.nextInt();
double result = 1.0;
final StringBuilder sb = new StringBuilder("1/1");
for (int index = 2, sign = -1; index <= value; index++, sign *= -1) {
sb.append(sign > 0 ? '+' : '-').append("1/").append(index);
result += (1.0 / (index * sign));
}
if (value != 0) {
sb.append("=").append(result);
System.out.println(sb.toString());
}
}
}
}
应该差不多了,只是不要有非法数据
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯