Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 82

C Exercise 82

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Convert octal to decimal

**Analysis:** None.

Example

// Created by www.runoob.com on 15/11/9.

// Copyright (c) 2015 Runoob Tutorial. All rights reserved.

//

#include

<

stdio.h

#include

<

math.h

#include

<

string.h

// Function declaration

int

octalToDecimal

(

const

char

octalNumber

)

;

int

main

(

)

{

char

octalNumber

[

100

]

;

// Input an octal number

printf

(

"

Please enter an octal number:

"

)

;

scanf

(

"

%s

"

,

octalNumber

)

;

// Convert to decimal

int

decimalNumber

=

octalToDecimal

(

octalNumber

)

;

// Output result

printf

(

"

The octal number %s converted to decimal is: %d

\

n

"

,

octalNumber

,

decimalNumber

)

;

return

0

;

}

// Function to convert octal to decimal

int

octalToDecimal

(

const

char

octalNumber

)

{

int

decimalNumber

=

0

;

int

length

=

strlen

(

octalNumber

)

;

for

(

int

i

=

0

;

i

<

length

;

i

++

)

{

int

digit

=

octalNumber

[

i

]

0

';

// Convert a character to a digit

decimalNumber

+=

digit

pow

(

8

,

length

i

1

)

;

}

return

decimalNumber

;

}

The above example produces the following output:



请输入一个八进制数: 16

八进制数 16 转换为十进制数是: 14

Code analysis:

- Define a character array `octalNumber` to store the octal number entered by the user. - Use the `scanf` function to get the octal number entered by the user. - Call the `octalToDecimal` function to convert the octal number to a decimal number. - Use the `printf` function to output the converted decimal number. - The `octalToDecimal` function receives the string representation of an octal number and converts it to a decimal number. - Use `strlen` to get the length of the octal string. - Traverse the octal string, converting each character to its corresponding digit and accumulating its decimal value into `decimalNumber`.

100 Classic C Language Examples 100 Classic C Language Examples