卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章18057本站已运行3329

十进制转二进制的C语言程序实现

十进制转二进制的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("<p> The Binary value is : %ld</p><p></p><p>",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;;
}</p>

输出

当执行上述程序时,会产生以下结果 -

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

现在,尝试将二进制数转换为十进制数。

示例

以下是将二进制数转换为十进制数的 C 程序 -

Live演示

'
#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<p>",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;
}</p>

输出

当执行上述程序时,会产生以下结果 -

'
Enter a binary number: 10011
The decimal value is:19
卓越飞翔博客
上一篇: 在C编程中以蛇形模式打印矩阵
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏