Skip to content

Latest commit

 

History

History
77 lines (51 loc) · 1.92 KB

File metadata and controls

77 lines (51 loc) · 1.92 KB

Java 程序:计算整数的位数

原文: https://www.programiz.com/java-programming/examples/digits-count

在此程序中,您将学习在 Java 中使用while循环和for循环来计算位数。

示例 1:使用while循环对整数中的位数进行计数

public class NumberDigits {

    public static void main(String[] args) {

        int count = 0, num = 3452;

        while(num != 0)
        {
            // num = num/10
            num /= 10;
            ++count;
        }

        System.out.println("Number of digits: " + count);
    }
}

运行该程序时,输出为:

Number of digits: 4

在此程序中,将循环while循环,直到测试表达式num != 0的值为 0(假)。

  • 第一次迭代后,num将除以 10,其值将为 345。然后,count增至 1。
  • 在第二次迭代后,num的值将为 34,并且count递增为 2。
  • 在第三次迭代后,num的值将为 3,并且count增至 3。
  • 第四次迭代后,num的值将为 0,并且count增至 4。
  • 然后将测试表达式求值为false并终止循环。

示例 2:使用for循环对整数中的位数进行计数

public class NumberDigits {

    public static void main(String[] args) {

        int count = 0, num = 123456;

        for(; num != 0; num/=10, ++count) {   
        }

        System.out.println("Number of digits: " + count);
    }
}

运行该程序时,输出为:

Number of digits: 6

在此程序中,不使用while循环,而是使用不带任何主体的for循环。

在每次迭代中,num的值除以 10,count则加 1。

num != 0为假,即num = 0时,for循环退出。

由于for循环没有主体,因此可以将其更改为 Java 中的单个语句,如下所示:

for(; num != 0; num/=10, ++count);