首页 > 解决方案 > 我如何计算在 C 中不使用 /10 的数字中的位数?

问题描述

我需要以二进制编码的十进制数计算位数,例如 00111001。我不能使用典型的 /10,因为它会卡在 2 个最后一个 0 上并且不计算它们。

#include <stdio.h>
#include <stdlib.h>
void main(void) {
    int bcd, digits;
    printf("Input BCD number: ");
    scanf_s("%d", &bcd);
    for (digits = 0; (bcd / 10) != 0; digits++)
        bcd /= 10;
    printf("Number of digits is %d", digits+1);
    getchar;
}

因此,如果我输入 1111 它显示“4”是正确的,但是当我输入 0011 时它显示“2”,那么我该如何解决呢?

标签: c

解决方案


当我输入 0011 时,它显示“2”,那么我该如何解决呢?

用于"%n"记录扫描的偏移量。

int n1;
int n2;
if (scanf_s(" %n%d%n", &bcd, &n1, &n2) == 1) {
  printf("Input %d\nNumber of digits is %d\n", bcd, n2 - n1);
}

推荐阅读