需求,求5的阶乘,代码实现如下:
使用递归的算法:
public class JieChengDemo {
public static void main(String[] args) {
System.out.println(jieCheng(5));
}
public static int jieCheng(int a){
if(a == 1){
return 1;
}else{
return a * jieCheng(a-1);
}
}
}
阶乘的其他算法:
public static void main(String[] args) {
int x = 1;
for(int y = 1; y <= 5; y++){
x = x * y;
}
System.out.println(x);
}
|
|