Java练习题(一)

1.  用户输入一个整数,请输出该整数的阶乘    例如:5!= =120

class Factorial{

    /**
     * @param args
     */
    public static void main(String[] args){
 
         int num;//整数
         int total = 1;//阶乘结果

         System.out.println("请输入一个整数");
         Scanner scanner = new Scanner(System.in);

         num = scanner.nextInt();

         for(int i = 1; i <= num;i++){

            total *= i; 

         }
  
         System.out.printf("%d!阶乘的结果为:%d",num,total);
    }

}

2.  输出99乘法表

class Multiplication{

    /**
     * @param args
     */

    public static void main(String[] args){

        for(int i = 1 ;i <= 9;i++){

            for(int j = 1; j <= i;j++){

                 System.out.printf("%d * %d = %d ",j,i ,j * i);
 
            }     

            System.out.println();

       }

      for(int i = 1 ;i <= 9;i++){


            for(int j = i; j >= 1;j--){


                 //System.out.printf("%d * %d = %d ",j,i ,j * i);
                 System.out.printf("%d * %d = %d ",(i-j + 1),i ,(i-j + 1) * i);
 
            }     


            System.out.println();


       }
    }

}

3.  编程输出所有的三位水仙花数 水仙花数:各位数字的立方数相s加等于该数本身  例如 153  1*1*1+5*5*5+3*3*3=153  153就是一个三位水仙花数

class Daffodil{

   /**
    * @param args
    * 
    * 程序入口
    */
    public static void main(String[] args){

         for(int i = 100;i <= 1000;i++){
           int total = 0;//各位数值之和 
           int temp = i;保存当前值
           while(temp != 0){

                total = (int) (total + Math.pow(temp%10,3));
                temp = temp / 10;
          }

          if(total == i){

              System.out.println(total+"是水仙花数");

          }

       }
	   
	   /*for(int i = 0;i <= 1000;i++){
		   
		   int a = i%10;//个位
		   int b =(i - a)%100/10;//十位
		   int c = (i-b*10 -a)/100;//百位
		   int total = (int)(Math.pow(a,3)+ Math.pow(b,3)+ Math.pow(b,3));
		   if(i == total){
			   
			   System.out.println(i+"是水仙花数");
		   }
		   
	   }*/

    }

}

4.计算圆周率

中国古代数学家研究出了计算圆周率最简单的办法:

PI=4/1-4/3+4/5-4/7+4/9-4/11+4/13-4/15+4/17......

这个算式的结果会无限接近于圆周率的值,我国古代数学家祖冲之计算出,圆周率在3.1415926和3.1415927之间,请编程计算,要想得到这样的结果,他要经过多少次加减法运算?

18660304

lass MathPI{
	
	public static void main(String[] args){
		
		double PI = 0.0;
		int count = 1;
		int negative = -1;
		
		while(PI <= 3.1415926 || PI >= 3.1415927){
			negative *= (-1);
			PI += negative * 4/(2 * count - 1);
			count++;
		}
		System.out.println("经过加减法运算次数为"+(--count));
	}
	
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值