Java语法基础练习题

来源:互联网 发布:中文翻译日文软件 编辑:程序博客网 时间:2024/06/05 18:59

练习1:

使用公式C=(5/9)F-32)打印下列华氏温度与摄氏温度对照表。

0      -17

20     -6

40     4

60     15

80     26

100    37

120    48

140    60

160    71

180    82

200    93

220    104

240    115

260    126

280    137

300    148

思考:

加入制表符使数据输出更整齐;

让摄氏温度保留一位小数。


public class Lesson1 {

 

public static void main(String[] args) {

// TODO Auto-generated method stub

/*Scanner input=new Scanner(System.in);

int f=input.nextInt();*/

     for(int i=300;i<=0;i-=20){

      double  num=  (((double)5/9)*(i-32));

      String  temp=String.format("%.1f", num);//让摄氏温度保留一位小数

      System.out.println(i+" "+temp);

     }

}

 

}

 

 

 修改温度转换程序,要求以逆序(从300度到0度的顺序)打印温度转换表。

public class Lesson1 {

 

public static void main(String[] args) {

// TODO Auto-generated method stub

/*Scanner input=new Scanner(System.in);

int f=input.nextInt();*/

     for(int i=300;i>=0;i-=20){

      double  num=  (((double)5/9)*(i-32));

      String  temp=String.format("%.1f", num);

      System.out.println(i+" "+temp);

     }

}

 

}

 


练习2:

打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153 是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。

public static void main(String[] args) {

        int temp=0;

        for (int i = 100; i < 999; i++) {

            temp=i;

            int x = temp % 10;//取个位的值

            temp = temp / 10;

            int y = temp % 10;//取十位的值

            int z = temp / 10;//取个位的值

            if (i == x * x * x + y * y * y + z * z * z) {

                System.out.print(i+"\t");

            }

        }

}

 

练习3:

1+2!+3!+...+20!的和

 public class JieCheng

 {

    public static void main(String[] args)

     {

         long sum=0;//因为数太大要定义成long类型

         long n=1;

          int i=1;

          for (i=1; i<=20 ;i++ )

         {

             n*=i;//此处是计算每个项的阶乘

             sum+=n;//此处是把每个项的阶乘数依次相加

         }

         System.out.println("所有阶乘数的和为:"+sum);

     }

 }