在这个 C 程序中,我们需要将二进制数转换为十进制数。使用 C 程序将二进制数转换为十进制数非常简单。
二进制数是仅由零和一表示的数字。二进制数用下标 2 表示,十进制数用下标 10 表示。例如:1001,10010,001。
为了将二进制数转换为十进制数,我们使用 while 循环。该程序的逻辑是首先从用户读取二进制数,然后使用 while 循环检查 num > 0,然后计算以下内容
rem = num
dec = dec + rem * base
num = num / 10
base = base * 2.
之后,使用 printf 将二进制数显示为 dnum,十进制等效数显示为 dec。
while (testExpression)
{
// codes inside the body of a while
}
While 循环评估测试表达式。如果测试表达式为真,则执行 while 循环内的代码并再次评估测试表达式。此过程一直持续到测试表达式变为假。当测试表达式为假时,while 循环终止。
步骤 1:包含头文件以在 C 程序中使用内置头文件。
步骤 2:声明整数变量 num,bnum,dec,base,rem。
步骤 3:将二进制数读入 num。
步骤 4:赋值 bnum=num。
步骤 5:使用 while 循环,条件为 num > 0,执行步骤 6。
步骤 6:rem=num,dec=dec+rem*base,num=num/10 和 base=base*2。
步骤 7:将二进制数显示为 bnum ,十进制等效数显示为 dec。
#include <stdio.h>
void main() {
int num, bnum, dec = 0, base = 1, rem;
printf("Enter the binary number(1s and 0s)\n");
scanf("%d", & num); /*Enter maximum five digits or use long int*/
bnum = num;
while (num > 0) {
rem = num%10;
dec = dec + rem * base;
num = num / 10;
base = base * 2;
}
printf("The Binary number is = %d\n", bnum);
printf("Its decimal equivalent is =%d\n", dec);
} /* End */
Enter the binary number(1s and 0s) 1010 The Binary number is = 1010 Its decimal equivalent is =10