12以内阶乘、自然对数e及e的x次方的计算(Factorial)
2016-06-20 16:36
369 查看
调试了1个多小时的小程序,突然感觉科学计算不是这么容易的事。
说明:
1. 不支持12以上的阶乘计算,如,计算13的阶乘时,数字不准确(超过int变量所支持的最大值2147483648而溢出)
2. 计算e时,数字越大,计算出的e的精度越高。用12的阶乘计算时,精确度为小数点以后9位,即2.718281828
代码如下:
运行结果:
请输入数字n:12
请输入数字x:2
数字12的阶乘为:479001600
使用数字12计算的自然对数为:2.718281828
使用数字12计算的e^x为:7.389054567
说明:
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
相关文章推荐
- 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
- 可爱且功能增强版的银行储存系统
- 杂记,待丰富-2016.06.20
- 数据结构_P19
- java.lang.IllegalStateException: Cannot start this animator on a detached view!
- etcd安装测试
- DHTML:<select>
- swiper的基础使用(八)
- linux 开启 自动挂载U盘 权限的设置
- jQuery操作Form表单元素
- 12步入门Python中的decorator装饰器使用方法
- PageRank简介,跟不懂的同学们一起分享一下
- 用ChemDraw如何对齐所有行和列
- 3-5显示和隐藏(display属性)
- 怎么批量设置EDIUS中的图片持续时间
- 按行读取ANSI、UNICODE 、UNICODE big endian、UTF-8四种文本文
- Thinkphp开源框架如何使用?
- 加载刷新布局
- 数据结构_P18
- Spring 定时器