int x = 10; for(int y = x - 1; y >= 1; y--) { x = x * y; } System.out.println(x); 从10乘到1的阶乘写法. long js = 1; for(int i = 1; i <= 10; i++) { js = js * i; } System.out.println(js); 从1乘到10的写法
循环从1乘到20,要注意的就是结果可能会很大,长度超出int类型的范围,所以定义乘积的时候用long. 代码如下: public class Practice3 { public static void main(String args[]){ long result=1; for(int i=1;i<=20;i++) result=result*i; System.out.println("20的阶乘为"+result); } } 效果如图:
计算阶乘的和 //阶乘的和,5!+4!+3!+2! int a = 5; for(int b = 4; b > 0; b--) { a = a * b; } //先定义好最大数的阶乘是多少 int c = a; for(int n = 5; n > 1; n--) //当n等于2的时候,这是算的就是1的阶乘,所以后面取n>1 { a = a / n; //利用数学公式,n! = (n + 1)!/(n + 1),再写出for循环计算 c = c + a; //重新定义c的值为每次相加的和
编写程序,用while语句计算1+1/2!+1/3!……+1/20!,并在控制泰山输出计算结果.要求1+1/2!+1/3!……+1/20!,其实就是求1+1*1/2+1*1/2*1/3+……+1*1/2*1/3*……*1/20. import java.math.BigDecimal; public class Jiecheng { public static void main(String args[]) { BigDecimal sum = new BigDecimal(0.0); //
一.该程序是用来测输入数据的平均值和方差的 公式: 二. 项目流程: 1. State the problem假定所有测量数为正数或者0,计算这一系列测量数的平均值和方差.假定我们预先不知道有多少测量数据被录入,一个负数标志着测量数据输入结束 2. Define the inputs and outputs程序要求输入的数是未知的正数或者0,程序输出的数是输入数据集的平均值和方差.除此之外,我们将打印出输入的数据数,因为它对于我们检查输入数据是有用的 3.Define the algorithm