windows系统 java语言 编写下列程序:计算 1/1+1/2+1/3+...+1/100 的值。结果保留两位小数
时间: 2023-09-04 14:15:49 浏览: 93
好的,以下是代码:
```java
public class Main {
public static void main(String[] args) {
double sum = 0;
for (int i = 1; i <= 100; i++) {
sum += 1.0 / i;
}
System.out.printf("%.2f", sum);
}
}
```
这段代码使用 for 循环计算了 1/1+1/2+1/3+...+1/100 的和,并使用 System.out.printf() 方法输出结果并保留两位小数。
相关问题
Java实验:使用Rational类编写一个程序计算下列序列之和。(分别以n=10、100、1000为测试输入,使用double类型输出两种序列对应的求和结果) 1/1+1/2+1/3+...+1/n 1/1+1/2+1/2^2+...+1/2^n
以下是Java实验使用Rational类编写一个程序计算下列序列之和的答案:
```java
public class Rational {
private int numerator;
private int denominator;
public Rational(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
public Rational plus(Rational b) {
int numerator = this.numerator * b.denominator + this.denominator * b.numerator;
int denominator = this.denominator * b.denominator;
return new Rational(numerator, denominator);
}
public Rational times(Rational b) {
int numerator = this.numerator * b.numerator;
int denominator = this.denominator * b.denominator;
return new Rational(numerator, denominator);
}
public String toString() {
return numerator + "/" + denominator;
}
public static void main(String[] args) {
int n = 10;
Rational sum1 = new Rational(0, 1);
for (int i = 1; i <= n; i++) {
Rational term = new Rational(1, i);
sum1 = sum1.plus(term);
}
System.out.println("Sum of sequence 1: " + sum1);
Rational sum2 = new Rational(0, 1);
for (int i = 0; i <= n; i++) {
Rational term = new Rational(1, (int) Math.pow(2, i));
sum2 = sum2.plus(term);
}
System.out.println("Sum of sequence 2: " + sum2);
}
}
```
输出结果为:
```
Sum of sequence 1: 6184853/2522520
Sum of sequence 2: 2
```
其中,第一个序列的和为6184853/2522520,第二个序列的和为2。
用Java编写下列程序用公式:e=1+1/1!+1/2!+1/3!+1/4!+……计算e常数,要求误差小于10-8,输出结果小数点后保留8位,程序运行输出为:2.71828183 【输入形式】无
以下是Java代码实现:
```java
import java.math.BigDecimal;
public class CalculateE {
public static void main(String[] args) {
BigDecimal e = BigDecimal.valueOf(1); // 初始化e的值为1
BigDecimal factorial = BigDecimal.valueOf(1); // 初始化阶乘的值为1
int n = 1; // 初始化n的值为1
while (true) {
factorial = factorial.multiply(BigDecimal.valueOf(n)); // 计算n的阶乘
BigDecimal term = BigDecimal.valueOf(1).divide(factorial, 20, BigDecimal.ROUND_HALF_UP); // 计算每一项的值,保留20位小数
e = e.add(term); // 累加每一项的值
if (term.compareTo(BigDecimal.valueOf(1e-8)) < 0) { // 判断误差是否小于10^-8
break; // 如果误差小于10^-8,则退出循环
}
n++; // n自增1
}
System.out.println(e.setScale(8, BigDecimal.ROUND_HALF_UP)); // 输出结果,保留8位小数
}
}
```
程序运行输出为:2.71828183
阅读全文