4循环控制
- 4.1 for循环
- 4.1.1 for循环
- 固定次数for循环
- 先执行一次do-while循环
- 其他while循环
-
Scanner in = new Scanner(System.in);//计算阶乘 int n = in.nextInt(); int factor = 1; ; for (int i = 1; i <= n; i++) { // factor=i*factor; factor *= factor; } System.out.println(n + "的阶乘值为:" + factor);
- 4.1.2 复合赋值
- a*=6 -> a=a*6
- a/=b+6 -> a=a/(b*6)
- i=i+1 ->i i++
-
1 Scanner in = new Scanner(System.in);//判断素数 2 int n = in.nextInt(); 3 int flag = 0; 4 for (int i = 2; i < n; i++) 5 { 6 if (n % i == 0) 7 { 8 flag = 1; 9 break; 10 } 11 } 12 if (flag == 1) 13 { 14 System.out.println(n + "不是素数!"); 15 } else 16 { 17 System.out.println(n + "是素数!"); 18 }
- 4.1.1 for循环
- 4.2循环控制
- 4.2.1循环控制
- 素数判断
-
1 for (int n = 2; n < 100; n++)//输出100以内的素数 2 { 3 int flag = 1; 4 for (int i = 2; i < n; i++) 5 { 6 if (n % i == 0) 7 { 8 flag = 0; 9 break; 10 } 11 } 12 if (flag == 1) 13 { 14 System.out.print(n + " "); 15 } 16 }
- break跳出循环
- continue跳出循环这一轮的语句进入下一轮
- 4.2.2多重循环
- lable:
- 标号标示循环,break lable或 continue lable 可以跳出
-
1 int count = 1;//输出前59个素数 2 int n = 2; 3 while (count <= 50) 4 { 5 int flag = 1; 6 for (int i = 2; i < n; i++) 7 { 8 if (n % i == 0) 9 { 10 flag = 0; 11 break; 12 } 13 } 14 if (flag == 1) 15 { 16 System.out.println("第" + count + "个素数:" + n); 17 count++; 18 } 19 n++; 20 }
- 4.2.3逻辑类型
- 按照优先级排列
- !
- &&
- ||
-
1 Scanner in = new Scanner(System.in);//凑硬币 2 int amount = in.nextInt(); 3 OUT: for (int one = 0; one <= amount; one++) 4 { 5 for (int five = 0; five <= amount / 5; five++) 6 { 7 for (int ten = 0; ten <= amount / 10; ten++) 8 { 9 for (int twenty = 0; twenty <= amount / 20; twenty++) 10 { 11 if ((one + 5 * five + 10 * ten + 20 * twenty) == amount) 12 { 13 System.out.println(one + "张1元," + five + "张5元," + ten + "张10元," + twenty + "张20元"); 14 break OUT; 15 } 16 } 17 } 18 } 19 }
- 4.2.1循环控制
- 4.3循环的例子
- 4.3.1求和
-
1 Scanner in = new Scanner(System.in);// f=1-1/2+1/3...求和 2 int n = in.nextInt(); 3 double sum=0; 4 int sign=1; 5 for (int i = 1; i <= n; i++,sign=-sign) 6 { 7 sum+=sign*1.0/i; 8 } 9 System.out.println("和为:"+sum); 10 System.out.print("和为:"); 11 System.out.printf("%.2f",sum);
-
- 4.3.2最大公约数
-
1 Scanner in=new Scanner(System.in);//求最大公约数 2 int a=in.nextInt(); 3 int b=in.nextInt(); 4 int gcd=1; 5 // for(int i=2;i<=a&&i<=b;i++) 6 for (int i = 2; i <= (a<b?a:b); i++) 7 { 8 if((a%i==0)&&(b%i==0)) 9 { 10 gcd=i; 11 } 12 } 13 System.out.println(a+"和"+b+"最大公约数为:"+gcd);
-
1 Scanner in=new Scanner(System.in);//辗转相除法求最大公约数 2 System.out.println("请输入a和b:"); 3 int a=in.nextInt(); 4 int b=in.nextInt(); 5 6 while (b!=0) 7 { 8 int r=a%b; 9 System.out.println(a+" "+b+" "+r); 10 a=b; 11 b=r; 12 } 13 System.out.println("最大的公约数为:"+a);
-
- 4.3.1求和