我有一个java程序,它使用for循环来计算整数中的数字
它返回给我的数字计数减 1
例如。
if i enter 6 digit integer it returns count of 5
if I enter 10 digit integer it returns count of 9
public class DigitCount {
public static void main(String[] args) {
int a=123456;
int count=0;
for (int i=0;i<=a;i++){
a=a/10;
count++;
}
System.out.println(" numb of digits are : "+ count);
}
}
以下是如何修复程序以正确计算位数:
public class DigitCount {
public static void main(String[] args) {
int a = 123456;
int originalNumber = a; // Store the original number
int count = 0;
while (a != 0) {
a = a / 10;
count++;
}
System.out.println("Number of digits in " + originalNumber + " are: " + count);
}
}