
如何使用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">
<a class="aritcle_card_img" href="/ai/950">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680003823895.png" alt="ViiTor实时翻译">
</a>
<div class="aritcle_card_info">
<a href="/ai/950">ViiTor实时翻译</a>
<p>AI实时多语言翻译专家!强大的语音识别、AR翻译功能。</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="ViiTor实时翻译">
<span>116</span>
</div>
</div>
<a href="/ai/950" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="ViiTor实时翻译">
</a>
</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
以上就是十进制转二进制的C语言程序实现的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号