代碼實現:while循環下的進制轉換

原理

好比12轉成2進制,那麼第一次模2後,獲得應該是最左邊位置的數,而後除2,以後再模2,獲得的是左邊第2個位置的數。數組

以下:code

12 % 2 = 0input

12 / 2 = 6io

6 % 2 = 0for循環

6 / 2 = 3原理

3 % 2 = 1循環

3 / 2 = 1 (向下取整)二進制

1 % 2 = 1di

1 / 2 = 0while

至此結束。

若是用一個數組來記錄,取模的值,那麼應該是:

0 0 1 1 0

這是逆序的。

因此反過來(for循環從右往左就行),

獲得的是01100,就是二進制的12

這種思想能夠進行推廣,使用與任何其餘進制

寫一個實現代碼

#include <cstdio>

int main()
{
    int N, D;
    printf("Please input you number and radix you wan to convert: \n");
    printf("Number(>0) : \n");
    scanf("%d", &N);
    printf("Radix(>0 && <=10): \n");
    scanf("%d", &D);
    int d[100], len = 0;
    do {
        d[len++] = N % D;
        N /= D;
    }while (N != 0);
    printf("Result:\n");
    for (int i = len - 1; i >= 0; i--) {
        printf("%d", d[i]);
    }
    printf("\n");
    return 0;
}
相關文章
相關標籤/搜索