编程练习4

题目:求1!+2!+3!+……+10!

思路:先求每个数字的阶乘n!=num,再将num相加。

代码:

 1 public class Factorial {
2 public static void main(String[] args) {
3 int sum = 0;
4 int num = 1;
5 for (int i=1; i<=10; i++)
6 {
7 num = num * i;
8 sum = sum + num;
9 }
10
11 System.out.println(sum);
12 }
13 }

结果:sum = 4037913

为了便于理解,我们每算一个阶乘,就打印加到这个阶乘为止的和

 1 public class Factorial {
2 public static void main(String[] args) {
3 int sum = 0;
4 int num = 1;
5 for (int i=1; i<=10; i++)
6 {
7 num = num * i;
8 sum = sum + num;
9 System.out.println("i = " + i);
10 System.out.println("num = " + num);
11 System.out.println("sum = " + sum);
12 }
13 }
14 }

结果:

 

注意:sum,num和i的初始值。

posted @ 2012-04-05 21:50  水芊芊  阅读(196)  评论(0编辑  收藏  举报