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

本文介绍了一个Java小程序,用于计算数字的阶乘、自然对数e及其指数e^x。程序采用循环实现阶乘计算,并通过公式逼近e及e^x的值。测试结果显示,随着输入数字增大,e的计算精度提高。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

调试了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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值