使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP