12以内阶乘、自然对数e及e的x次方的计算(Factorial)

时间:2021-06-25 18:34:03

调试了1个多小时的小程序,突然感觉科学计算不是这么容易的事。


说明:

1. 不支持12以上的阶乘计算,如,计算13的阶乘时,数字不准确(超过int变量所支持的最大值2147483648而溢出)

2. 计算e时,数字越大,计算出的e的精度越高。用12的阶乘计算时,精确度为小数点以后9位,即2.718281828


代码如下:

//JHTP Exercise 4.37: Factorial
//by pandenghuang@163.com
/*(Factorial) The factorial of a nonnegative integer n is written as n! (pronounced “n factorial”)
and is defined as follows:
n! = n · (n – 1) · (n – 2) · … · 1 (for values of n greater than or equal to 1)
and
n! = 1 (for n = 0)
For example, 5! = 5 · 4 · 3 · 2 · 1, which is 120.
a) Write an application that reads a nonnegative integer and computes and prints its factorial.
b) Write an application that estimates the value of the mathematical constant e by using
the following formula. Allow the user to enter the number of terms to calculate.
c) Write an application that computes the value of e^x by using the following formula. Allow
the user to enter the number of terms to calculate.*/
import java.util.Scanner;

public class Factorial
{
public static int factorial(int n){
int factorial=n;
int counter=n;
while (counter>1){
factorial*=counter-1;
counter--;
}
return factorial;
}

public static double e(int n){
double e=1.0;
int counter=1;
while (counter<=n){
e+=(double)1/factorial(counter);
counter++;
}
return e;
}

public static double ex(int n,int x){
double ex=1.0;
int counter=1;
while (counter<=n){
ex+=(double)Math.pow(x,counter)/factorial(counter);
counter++;
}
return ex;
}

public static void main(String[] args)
{
int number=1;
int x=1;
int factorial=1;
double e=1.0;
double ex=1.0;


Scanner input=new Scanner(System.in);

System.out.print("请输入数字n:");
number=input.nextInt();
System.out.print("请输入数字x:");
x=input.nextInt();
factorial=factorial(number);
e=e(number);
ex=ex(number,x);

System.out.printf("数字%d的阶乘为:%d\n",number,factorial);
System.out.printf("使用数字%d计算的自然对数为:%.9f\n",number,e);
System.out.printf("使用数字%d计算的e^x为:%.9f\n",number,ex);
}
}


运行结果:

请输入数字n:12
请输入数字x:2
数字12的阶乘为:479001600
使用数字12计算的自然对数为:2.718281828
使用数字12计算的e^x为:7.389054567