在java中为什么在算阶乘是 要在int变量的数据减48在参加运算
解决方案 »
- tcp 传输问题
- 关于JAR运行时classpath的问题
- 枚举算是一种自定义的得分数据类型吗?没觉得enum好
- Workbook读取EXCEL设置时间格式
- 请问 thinking in java(java编程思想) 这本书的市面最新版本是?
- 关于接口????
- Exception in thread "main" java.lang.NoSuchmethodError:main这是什么错?
- 关于package的问题
- java bean放入orsin和tomcat的什么目录下?
- 我想请教一下关于iReport生成二维码的问题
- 文本文件内关键字提取
- 哪个高手能帮下.怎么写(最好用java或js写)
这应该是基本代码了,与之共勉。
这是利用简单的循环相乘制造的阶乘。
public class Factorial {
public static int factorial(int x) {
if (x < 0) {
throw new IllegalArgumentException("x must be>=0");
}
int fact = 1;
for (int i = 2; i <= x; i++) {
fact *= i;
}
return fact;
} public static void main(String args[]) { System.out.print(factorial(10));
}
}这个是利用递归算法制成的。public class factorial2 {
public static int factorial2(int x) {
if (x < 0) {
throw new IllegalArgumentException("x must be>=0");
}
if (x <= 1) {
return 1;
} else
return x * factorial2(x - 1);
}
public static void main(String args[]) { System.out.print(factorial2(17));
}
}这个是数组添加的方法制成的,可以计算更大的阶乘。public class Factorial3 {
static long[] table = new long[21];
static {table[0] = 1; } static int last = 0;
public static long factorial(int x) throws IllegalArgumentException {
if (x >= table.length) {
throw new IllegalArgumentException("Overflow; x is too large.");
}
if (x <= 0) {
throw new IllegalArgumentException("x must be non-negative.");
} while (last < x) {
table[last + 1] = table[last] * (last + 1);
last++;
}
return table[x];
}
public static void main(String[] args) {最后一个是利用BigInteger类制成的,这里可以用更大的更大的阶乘。import java.math.BigInteger;
import java.util.*;
public class Factorial4{
protected static ArrayList table = new ArrayList();
static{ table.add(BigInteger.valueOf(1));} public static synchronized BigInteger factorial(int x){
for(int size=table.size();size<=x;size++){
BigInteger lastfact= (BigInteger)table.get(size-1);
BigInteger nextfact= lastfact.multiply(BigInteger.valueOf(size));
table.add(nextfact);
}
return (BigInteger) table.get(x);
}
} System.out.print(factorial(20));
}
}
class Test7{
public static void main(String[] args)throws IOException{
int i,n,sum=1;
System.out.println("Please input(0~~15):");
n=System.in.read();
n-=48;
for(i=1;i<=n;i++)
sum*=i;
System.out.println(n+"!="+sum);
}
}
这就是我要问的代码为什么n-=48 在参加运算
读取的是字符的ascii码。
说明:
return
the next byte of data, or -1 if the end of the stream is reached.