这个程序从用户那里取一个整数并计算位数。例如: 如果用户输入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中。然后
第一次迭代后,n 的值为 345,do...while
loop 被迭代直到测试表达式
n! = 0
被评估为 0(假)。
count
增加到 1、
第二次迭代后,n 的值为 34,count
增加到 2、
第三次迭代后,n 的值为 3,count
增加到 3、
第四次迭代后,n 的值为 0,count
增加到 4、
然后循环的测试表达式被评估为假并且循环终止。
注意: 我们使用了一个 do...while 循环来确保当用户输入 0 时我们得到正确的数字计数。