读入一个小于100的整数,求这个整数的阶乘(result)!!
(未完成代码)
Scanner sc = new Scanner(System.in);
System.out.print("请输入一个100以内整数:");
int n=sc.nextInt();
int result=1;
for(int i=1;i<=n;i++)
result*=i;
System.out.println(result);
就是运行以后,如果输入的数小于100,则输出结果,程序终止;
如果输入的数大于100;则提示System.out.println("数值超出允许范围,请重新输入:");然后用户再输入一个数,如果符合要求则输出结果,反之再次提醒重新输入,直至符合要求,然后程序终止;基础,阶乘,循环,求助
(未完成代码)
Scanner sc = new Scanner(System.in);
System.out.print("请输入一个100以内整数:");
int n=sc.nextInt();
int result=1;
for(int i=1;i<=n;i++)
result*=i;
System.out.println(result);
就是运行以后,如果输入的数小于100,则输出结果,程序终止;
如果输入的数大于100;则提示System.out.println("数值超出允许范围,请重新输入:");然后用户再输入一个数,如果符合要求则输出结果,反之再次提醒重新输入,直至符合要求,然后程序终止;基础,阶乘,循环,求助
System.out.println("输入整数超出范围,请重新输入:"); n = scan.nextInt();
}
BigDecimal a = new BigDecimal(1);
for(int i = 1 ; i < n ; i++){
a = a.multiply(new BigDecimal(i));
}
如:
while(true) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入一个100以内整数:");
int n=sc.nextInt();
if (n <= 100) { //当小于等于100时跳出循环
break;
}
System.out.println超("数值允许范出围,请重新输入:");
}
在32位机上,int类型的字节数是2的32次方=4294967296(无符号),带符号再除以2,负数比正数多一个,-2147483648~+2147483647,计算超出13阶层就溢出了.
import java.util.Scanner;public class TestTop {
/*public long show(long n){//计算大于70的数字时超出long的最大数字,会返回0
if (n==0 || n==1) {
return n;
}else{
//System.out.println(n);
return n*show(n-1);
}
}*/
public BigInteger getFactorial(int n) {//这个方法可以精确的计算.
if (n < 0) {
System.err.println("n必须大于等于0!");
return new BigInteger("-1");
} else if (n == 0) {
return new BigInteger("0");
}
//将数组换成字符串后构造BigInteger
BigInteger result = new BigInteger("1");
for (; n > 0; n--) {
//将数字n转换成字符串后,再构造一个BigInteger对象,与现有结果做乘法
result = result.multiply(new BigInteger(new Integer(n).toString()));
}
return result;
}
public static void main(String args[]) {
// TODO Auto-generated method stu
TestTop t =new TestTop();
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个整数:");
int s = sc.nextInt();
if(s<100){
BigInteger b = t.getFactorial(s);
System.out.println(b);
}else{
System.out.println("您输入的数字不符合规则!");
}
}
}