C Language Practice: Octagonal to Decimal

From Eric & Company
Jump to navigation Jump to search

Convert: Octagonal to Decimal

  • Step 1: Get all the packs and the otod function
  • Step 2: Get the main function and call the otod function


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

int otod(char *o)
{
    int i;
    int d = 0;
    int p = 0, t = 0;

    for (i = strlen(o) - 1; i >= 0; i--)
    {
        if ((o[i] >= '0') && (o[i] <= '7'))
        {
            t = o[i] - '0';
        }
        else
        {
            printf("error: not a valid octagonal number\n");
            exit(0);
        }

        d += t * pow(8, p);
        p++;
    }

    return d;
}

int main(void)
{
    char o[100];
    printf("input an octal num: ");
    scanf("%s", o);

    printf("the decimal num for this octal num is: %d\n", otod(o));

    return 0;
}