簡體   English   中英

我如何在 C 中不使用 /10 計算數字中的位數?

[英]How do i count the number of digits in a number not using /10 in C?

我需要計算二進制編碼的十進制位數,例如 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”,那么我該如何解決呢?

當我鍵入 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);
}

如果您實際上使用的是二進制編碼的十進制,那么這將起作用:

unsigned short count_bcd_digits(unsigned bcd)
{
    unsigned short count = 0;

    do {
        count++;
    } while(bcd >>= 4);

    return count;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM