C Exercise Example 82
Title:Octal to decimal conversion
Program analysis:None.
Example
// Created by www.example.com on 15/11/9.
// Copyright © 2015 Example. 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 the results
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 output of the above example is:
请输入一个八进制数: 16 八进制数 16 转换为十进制数是: 14
Code Analysis:
- Header file: Include the necessary header files
stdio.h(for input/output),math.h(for mathematical calculations) andstring.h(for string operations). - Function Declaration:
int octalToDecimal(const char *octalNumber);Declared 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. - Usage
scanfThe function obtains the octal number entered by the user. - Call
octalToDecimalThe function converts an octal number to a decimal number. - Usage
printfThe function outputs the converted decimal number.
- Define a character array
- The function to convert octal to decimal:
octalToDecimalThe function receives a string representation of an octal number and converts it to a decimal number.- Usage
strlenGet the length of the octal string. - Iterate through the octal string, convert each character to the corresponding digit, and calculate its corresponding decimal value, accumulating to
decimalNumber。