Java经典习题(3)

来源:互联网 发布:js图片特效 编辑:程序博客网 时间:2024/05/02 00:27

11.中国古代算书《张丘建算经》中有一道著名的百鸡问题:公鸡每只值5 文钱,母鸡每只值3 文钱,而3 只小鸡值1 文钱。用100 文钱买100 只鸡,问:这100 只鸡中,公鸡、母鸡和小鸡各有多少只?

程序分析:这个题目需要利用嵌套的for循环来解决,x表示公鸡的只数,y表示母鸡的只数,z表示小鸡的只数。x、y、z都是从0循环到100,需要满足3个条件:a)x+y+z==100; b)5*x+3*y+z/3==100; c)z%3==0 。

public class Question11 {public static void main(String[] args) {for (int x = 1; x <= 20; x++) {for (int y = 1; y <= 33; y++) {for (int z = 1; z <= 100; z++) {if ((z % 3 == 0) && (x + y + z == 100)&& (5 * x + 3 * y + z / 3 == 100)) {System.out.println("公鸡有" + x + "只,母鸡有" + y + "只,小鸡有"+ z + "只。");}}}}}}


12.程序接收一个正整数n。

如果n=3,就打印

*

***

*****

如果n=4,就打印

*

***

*****

*******

程序分析:程序接收的正整数n即代表有多少行,现在的问题是求解对于行i来说,它应该打印多少个*号,我们可以发现一个规律,每行打印的*号的数量,是每次都累加2。

import java.util.Scanner;public class Question12 {public static void main(String[] args) {int n; // 代表总行数int m = -1; // 代表每行的*号数量System.out.println("请输入正整数n:");Scanner sc = new Scanner(System.in);n = sc.nextInt();for (int i = 1; i <= n; i++) {m = m + 2;for (int j = 1; j <= m; j++) {System.out.print("*");}System.out.println();}}}

13.编写Java程序输出99乘法表。

程序分析:首先我们来看一下99乘法表的样子,然后发现规律

1×1=1
1×2=2 2×2=4
1×3=3 2×3=6 3×3=9
1×4=4 2×4=8 3×4=12 4×4=16
1×5=5 2×5=10 3×5=15 4×5=20 5×5=25
1×6=6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
1×7=7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
1×8=8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
1×9=9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81

通过以上的表我们不难发现,一共有9行,每一行的行号i将作为乘数,而被乘数则从1变化到i。

public class Question13 {public static void main(String[] args) {for (int i = 1; i <= 9; i++) {for (int j = 1; j <= i; j++) {System.out.print(" " + j + "*" + i + "=" + (i * j) + " ");}System.out.println();}}}

14.程序接收一个正整数n,输出n各个位数上的数字相加之和。(注意n是任意位数)

程序分析:因为int类型表示的数值范围有限,所以不能用int来记录输入的正整数n,可以采用字符串String类型的变量来记录,然后将每个位上面的数字通过for循环读取出来累加。

public class Question14 {public static void main(String[] args) {System.out.println("请输入正整数n:");Scanner sc = new Scanner(System.in);String str = sc.next();int sum = 0;for (int i = 0; i < str.length(); i++) {String ch = str.substring(i, i + 1);int temp = Integer.valueOf(ch);sum += temp;}System.out.println(str + "的各个位数相加之和是:" + sum);}}


15.

计算圆周率:

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

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

这个算式的结果会无限接近于圆周率的值,我国古代数学家祖冲之计算出,圆周率在3.1415926和

3.1415927之间,请编程计算,要想得到这样的结果,他要经过多少次加减法运算?

程序分析:需要利用while循环来做,发现规律是被除数永远是4,而除数会每次递增2,所以程序如下:

public class Question15 {public static void main(String[] args) {final double a = 4.0; //表示被除数double PI = 0; //表示圆周率int b = -1; //表示除数int count = 0; //加减法次数计数变量while (PI >= 3.1415927 || PI <= 3.1415926) {b +=2;PI= PI+ a/b;count++;b +=2;PI = PI - a/b; count++;}System.out.println("总共需要经过" + count +"次加减法运算");}}



0 0
原创粉丝点击