1、求1+2!+3!+…+20!的和
public class Prog21{
public static void main(String[] args){
long sum = 0;
for(int i=0;i<20;i++)
sum += factorial(i+1);
System.out.println(sum);
}
//阶乘
private static long factorial(int n){
int mult = 1;
for(int i=1;i<n+1;i++)
mult *= i;
return mult;
}
}
2、有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。
public class Prog11{
public static void main(String[] args){
int count = 0;
int n = 0;
for(int i=1;i<5;i++){
for(int j=1;j<5;j++){
if(j==i)
continue;
for(int k=1;k<5;k++){
if(k!=i && k!=j){
n = i*100+j*10+k;
System.out.print(n+" ");
if((++count)%5==0)
System.out.println();
}
}
}
}
System.out.println();
System.out.println("符合条件的数共:"+count+"个");
}
}
3、输入某年某月某日,判断这一天是这一年的第几天?
import java.util.Scanner;
public class Prog14{
public static void main(String[] args){
Scanner scan = new Scanner(System.in).useDelimiter("\\D");//匹配非数字
System.out.print("请输入当前日期(年-月-日):");
int year = scan.nextInt();
int month = scan.nextInt();
int date = scan.nextInt();
scan.close();
System.out.println("今天是"+year+"年的第"+analysis(year,month,date)+"天");
}
//判断天数
private static int analysis(int year, int month, int date){
int n = 0;
int[] month_date = new int[] {0,31,28,31,30,31,30,31,31,30,31,30};
if((year%400)==0 || ((year%4)==0)&&((year%100)!=0))
month_date[2] = 29;
for(int i=0;i<month;i++)
n += month_date[i];
return n+date;
}
}
以下为该程序的分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天。