使用 C 程式語言進行十進位制轉二進位制


問題

如何使用 C 程式語言中的函式將十進位制數轉換為二進位制數?

解決方案

在此程式中,我們在 main() 中呼叫函式轉換為二進位制。呼叫的函式轉換為二進位制將會進行實際轉換。

我們使用的邏輯(稱為函式)將十進位制數轉換為二進位制數,如下所示 −

while(dno != 0){
   rem = dno % 2;
   bno = bno + rem * f;
   f = f * 10;
   dno = dno / 2;
}

最後,它將二進位制數返回給主程式。

示例

以下是將十進位制數轉換為二進位制數的 C 程式 −

 現場演示

#include<stdio.h>
long tobinary(int);
int main(){
   long bno;
   int dno;
   printf(" Enter any decimal number : ");
   scanf("%d",&dno);
   bno = tobinary(dno);
   printf("
The Binary value is : %ld

",bno);    return 0; } long tobinary(int dno){    long bno=0,rem,f=1;    while(dno != 0){       rem = dno % 2;       bno = bno + rem * f;       f = f * 10;       dno = dno / 2;    }    return bno;; }

輸出

執行以上程式時,將產生以下結果 −

Enter any decimal number: 12
The Binary value is: 1100

現在,嘗試將二進位制數轉換為十進位制數。

示例

以下是將二進位制數轉換為十進位制數的 C 程式 −

 現場演示

#include
#include <stdio.h>
int todecimal(long bno);
int main(){
   long bno;
   int dno;
   printf("Enter a binary number: ");
   scanf("%ld", &bno);
   dno=todecimal(bno);
   printf("The decimal value is:%d
",dno);    return 0; } int todecimal(long bno){    int dno = 0, i = 0, rem;    while (bno != 0) {       rem = bno % 10;       bno /= 10;       dno += rem * pow(2, i);       ++i;    }    return dno; }

輸出

執行以上程式時,將產生以下結果 −

Enter a binary number: 10011
The decimal value is:19

更新於: 2021 年 3 月 8 日

3K+ 瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始
廣告