C 程序:八进制转十进制

编写一个 C 程序,使用 while 循环将八进制转换为十进制。在此示例中,while 循环迭代并将值除以各位数,并且 decimal = decimal + (octal % 10) * pow(8, i++) 语句将八进制转换为十进制数。 

#include <stdio.h>
#include <math.h>

int main()
{
    int octal, decimal = 0;
    int i = 0;
    
    printf("Enter the Octal Number = ");
    scanf("%d",&octal);

    while(octal != 0)
    {
        decimal = decimal + (octal % 10) * pow(8, i++);
        octal = octal / 10;
    }

    printf("The Decimal Value = %d\n", decimal); 
    
    return 0;
}
Program to Convert Octal to Decimal

在此 程序 中,decimalToOctal 函数接受八进制数,并使用 for 循环将其转换为十进制。

#include <stdio.h>
#include <math.h>

long decimalToOctal(int octal)
{
    long decimal = 0, i = 0;

    while(octal != 0)
    {
        decimal = decimal + (octal % 10) * pow(8, i++);
        octal = octal / 10;
    }
    return decimal;
}
int main()
{
    int octal;
    int i = 0;
    
    printf("Enter the Number = ");
    scanf("%d",&octal);

   long deci = decimalToOctal(octal);

    printf("Result = %ld\n", deci); 
    
    return 0;
}
Enter the Number = 987
Result = 647


Enter the Number = 15
Result = 13