3循环
- 3.1循环
- 3.1.1循环
- 一直要做的行为进行循环
- 3.1.2数数字
- while(){}判断是否进行
- 数数字:number/10
-
1 //数数字
Scanner in = new Scanner(System.in); 2 System.out.println("请输入一个数!"); 3 int number = in.nextInt(); 4 int count = 0; 5 while (number > 0) 6 { 7 number = number / 10; 8 count++; 9 System.out.println("number=" + number + " count=" + count); 10 } 11 System.out.println("该数有" + count + "位!");
- 3.1.3while循环
- 测试数据
- 个位数
- 10
- 0
- 负数
-
1 Scanner in = new Scanner(System.in);//解决0的数数字 2 System.out.println("请输入一个数!"); 3 int number = in.nextInt(); 4 int count = 0; 5 do 6 { 7 number = number / 10; 8 count++; 9 System.out.println("number:" + number + " count:" + count); 10 } while (number > 0); 11 System.out.println("该数有" + count + "位");
- 测试数据
- 3.1.4do-while循环
- while();分号不能忘记
-
//计数循环 Scanner in = new Scanner(System.in); int count = 100; do { System.out.println(count); count = count - 1; } while (count > 0); System.out.println(count); System.out.println("发射!");
- 3.1.1循环
- 3.2循环的例子
- 计数循环
- 如果要模拟运行一个很大次数的循环,可以模拟较少的循环次数,然后作出判断。
- 算平均数
-
1 Scanner in = new Scanner(System.in);//计算平均数 2 int number; 3 int sum = 0; 4 int count = 0; 5 while ((number = in.nextInt()) != -1) 6 { 7 sum = sum + number; 8 count++; 9 } 10 if (count > 0) 11 { 12 System.out.println("平均数为:" + (double) sum / count); 13 14 }
-
- 猜数
-
1 Scanner in = new Scanner(System.in);//猜数游戏 2 int number = (int) (Math.random() * 100 + 1);// [0,1)-->[0,100)-->[1,100] 3 int a; 4 int count = 0; 5 while ((a = in.nextInt()) != number) 6 { 7 if (a > number) 8 { 9 System.out.println("大了"); 10 } else if (a < number) 11 { 12 System.out.println("小了"); 13 } 14 count++; 15 } 16 System.out.println("恭喜你猜对了,你猜了" + count + "次!");
-
- 整数分解
-
1 Scanner in = new Scanner(System.in);//整数分解 2 int number; 3 number = in.nextInt(); 4 int result = 0; 5 do 6 { 7 int digit = number % 10; 8 result = result * 10 + digit; 9 System.out.print(digit); 10 number = number / 10; 11 } while (number > 0); 12 System.out.println(); 13 System.out.println(result);
- n%10->得到个位
- n/10->去掉一位
-
- 计数循环