第4章 循环

4 习题解答

（b）循环 5 次 输出结果：3 5 7 9

2、运行结果：max is 5,number 0

3、

1、 public class C { public static double pi=3.1415926; public static void main(String[] args){ double area; for(int r=1;r<=10;r++){ area=pi*r*r; System.out.println("r="+r+"area="+area); if(area>100)break; } } } 2、 public class C { public static void main(String[] args){ int a,b; double n; for (a=2;a<=100;a++){ for (a=100;a<=200;a++){ n=Math.sqrt(a); for (b=2;b<=n;b++) if (a%b==0)break; if(b>n) System.out.println(a); } } } 3、 public class C { public static void main(String[] args){ char A,B,C; for(A=88;A<=90;A++) for(B=88;B<=90;B++) for(C=88;C<=90;C++) if(A!=88&&C!=88&&C!=90&&A!=B&&B!=C&&A!=C){ System.out.println("A will marry to "+A ); System.out.println("B will marry to "+B ); System.out.println("C will marry to "+C ); } } } 4、 import java.util.Scanner;

public class C { public static void main(String[] args) { Scanner In=new Scanner(System.in); int n; n=In.nextInt(); while(n!=1){ if(n%2==0){ n=n/2; System.out.println(n); } else{ n=n*3+1; System.out.println(n); } } } } 5、 import java.util.Scanner; public class C { public static void main(String[] args) { int m,n,l; Scanner In=new Scanner(System.in); m=In.nextInt(); n=In.nextInt(); l=m*n; while(m*n!=0){ if(m>=n) m=m%n; else n=n%m; } if(m==0){ System.out.println("最大公约数为"+n); System.out.println("最小公倍数为"+l/n); } if(n==0){ System.out.println("最大公约数为"+m); System.out.println("最小公倍数为"+l/m); } } } 6、 public class F {

public static void main(String[] args) { int r,y,g; for(r=0;r<=3;r++) for(y=0;y<=3;y++) for(g=2;g<=6;g++) if(r+y+g==8) System.out.println("红球"+r+"黄球"+y+"绿球"+g); } } 7、 public class C { public static void main(String[] args) { int a,b,c; for(a=0;a<34;a++) for(b=0;b<=50;b++){ c=100-a-b; if(a*3+b*2+c*0.5==100){ System.out.println("大马"+a+"中马"+b+"小马"+c); } } } } 8、 public class E { public static void main(String[] args) { double flag=0; for(int n=10000;n<=100000;n=n+10000){ double m = 0 ; for(int i=0;i<=n;i++){ if(i%2==0) flag=1; else flag=-1; m=m+flag/(2*i+1); } System.out.println("当i="+n+"时"+"π ="+4*m); } } } 如下性能更好： public class E { public static void main(String[] args) { double flag=0;double m = 0 ;

for(int n=0;n<=100000;n++){ if(n%2==0) flag=1; else flag=-1; m=m+flag/(2*n+1); if (n % 10000==0) System.out.println(" 当i="+n+"时"+"π ="+4*m); } } }