C Exercise 82
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:
- Header File: Include the necessary header files
stdio.h(for input and output),math.h(for mathematical calculations) andstring.h(for string operations). - Function declaration:
int octalToDecimal(const char *octalNumber);Declares a function that converts an octal number to a decimal number. - Main function:
- Define a character array
octalNumberto store the octal number entered by the user. - Use
scanfThe function gets the octal number entered by the user. - called
octalToDecimalThe function converts the octal number to a decimal number. - Use
printfThe function outputs the converted decimal number.
- Function to convert octal to decimal:
octalToDecimalThe function receives the string representation of an octal number and converts it to a decimal number.- Use
strlenGet the length of the octal string. - Traverse the octal string, convert each character to its corresponding digit, and accumulate its corresponding decimal value into
decimalNumber.