该程序使用用户定义的函数将八进制数转换为二进制数。
示例:将八进制转换为二进制的程序
在这个程序中,我们创建了一个用户定义的函数octalToBinary()
。此函数首先将八进制数(由用户输入)转换为十进制数,然后将该十进制数转换为二进制数。要了解该程序的工作原理,您应具备以下 C 编程主题的基本知识:
#include <stdio.h>
#include <math.h>
//This function converts octal number to binary number
long octalToBinary(int octalnum)
{
int decimalnum = 0, i = 0;
long binarynum = 0;
/* This loop converts octal number "octalnum" to the
* decimal number "decimalnum"
*/
while(octalnum != 0)
{
decimalnum = decimalnum + (octalnum%10) * pow(8,i);
i++;
octalnum = octalnum / 10;
}
//i is re-initialized
i = 1;
/* This loop converts the decimal number "decimalnum" to the binary
* number "binarynum"
*/
while (decimalnum != 0)
{
binarynum = binarynum + (decimalnum % 2) * i;
decimalnum = decimalnum / 2;
i = i * 10;
}
//Returning the binary number that we got from octal number
return binarynum;
}
int main()
{
int octalnum;
printf("Enter an octal number: ");
scanf("%d", &octalnum);
//Calling the function octaltoBinary
printf("Equivalent binary number is: %ld", octalToBinary(octalnum));
return 0;
}
输出:
Enter an octal number: 71
Equivalent binary number is: 111001
看看这些相关的 C 程序: