
问题
如何使用C语言中的函数将十进制数转换为二进制数?
解决办法
在在这个程序中,我们在 main() 中调用一个二进制函数。被调用的二进制数转换函数将执行实际的转换。
我们使用的将十进制数转换为二进制数的调用函数的逻辑如下 -
while(dno != 0){
rem = dno % 2;
bno = bno + rem * f;
f = f * 10;
dno = dno / 2;
}最后将二进制数返回给主程序。
立即学习“C语言免费学习笔记(深入)”;
示例
以下是将十进制数转换为二进制数的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><p> The Binary value is : %ld</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/2091" title="PPT.AI"><img
src="https://img.php.cn/upload/ai_manual/000/000/000/175679993381810.png" alt="PPT.AI" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/2091" title="PPT.AI">PPT.AI</a>
<p>AI PPT制作工具</p>
</div>
<a href="/ai/2091" title="PPT.AI" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><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;;
}输出
当执行上述程序时,会产生以下结果 -
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><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;
}输出
当执行上述程序时,会产生以下结果 -
Enter a binary number: 10011 The decimal value is:19










