您的位置:首页 > 编程语言 > Java开发

java练习笔记 2011.06.07

2011-06-08 15:53 162 查看
 

计算result=1!+...+10!

 

一、使用for循环

 

public class Factorial {
public static void main(String[] args) {
long result = 0;
long temp = 1;

for(int i=1; i<=10; i++) {
temp *= i;
result += temp;
}

System.out.println("result=" + result);
}
}
 

二、使用递归调用

public class Recursive {
public static void main(String[] args) {
long result = 0;

for (int i=1; i<=10; i++) {
long showResult = 0;
showResult = factorial(i);

System.out.println(i + "!=" + showResult);
result += showResult;
}

System.out.println("1!+...+10!=" + result);
}

public static long factorial(int number) {
if (number == 1) {
return 1;
} else {
return number * factorial(number - 1);
}
}
}
 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java string class