这是java版本的:package com.lian.Test;
import java.text.DecimalFormat;
import java.util.Scanner;
/**
* @author :LSS
* @description: 已知表达式,输入对应的数字,计算对应数字前n项的和,输入0程序结束
* @date :2021/6/29 15:16
*/
public class Test2 {
//保留两位的数据模板
private static DecimalFormat df = new DecimalFormat("######0.00");
/**
* 计算阶乘
* @param n
* @return
*/
public static long getFactorial(int n){
long result = 1;
if (n == 0 || n == 1)
return result;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
/**
* 计算1/0!+1/1!+...+1/n!的值
* @param n
* @return
*/
public static double getNumber(int n){
double result = 0;
for (int i = 0; i < n; i++) {
result += (1.0 / getFactorial(i));
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int [] ints = new int[10];
int flag = 0;
while (true){
int i = scanner.nextInt();
if (i == 0)
break;
ints[flag] = i;
flag++;
}
for (int i = 0; i < flag; i++) {
System.out.println(df.format(getNumber(ints[i])));
}
}
}
|