此程序从用户那里获取一个整数,并计算其位数。例如:如果用户输入 2319,则程序的输出将是 4。
计算位数程序
#include <stdio.h>
int main() {
long long n;
int count = 0;
printf("Enter an integer: ");
scanf("%lld", &n);
// iterate at least once, then until n becomes 0
// remove last digit from n in each iteration
// increase count by 1 in each iteration
do {
n /= 10;
++count;
} while (n != 0);
printf("Number of digits: %d", count);
}
输出
Enter an integer: 3452 Number of digits: 4
用户输入的整数存储在变量 n 中。然后,do...while
循环会一直迭代,直到测试表达式 n != 0
被评估为 0(false)。
- 第一次迭代后,n 的值为 345,
count
增加到 1。 - 第二次迭代后,n 的值为 34,
count
增加到 2。 - 第三次迭代后,n 的值为 3,
count
增加到 3。 - 第四次迭代后,n 的值为 0,
count
增加到 4。 - 然后,循环的测试表达式被评估为 false,循环终止。
注意:我们使用 do...while
循环是为了确保在用户输入 0 时也能得到正确的位数计数。