C语言计算整数位数数量的程序

要理解这个示例,您应该了解以下 C 编程 主题


此程序从用户那里获取一个整数,并计算其位数。例如:如果用户输入 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 时也能得到正确的位数计数。

在我们结束之前,让我们来检验一下你对这个例子的理解!你能解决下面的挑战吗?

挑战

编写一个函数来计算给定数字的位数。

  • 例如,对于输入 num = 12345,返回值应为 5。
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战