Skip to content

Latest commit

 

History

History
104 lines (79 loc) · 2.64 KB

95.md

File metadata and controls

104 lines (79 loc) · 2.64 KB

C++ 程序:将八进制数转换为十进制,反之亦然

原文: https://www.programiz.com/cpp-programming/examples/octal-decimal-convert

在此示例中,您将学习通过创建用户定义的函数来手动将八进制数转换为十进制,并将十进制数转换为八进制。

要理解此示例,您应该了解以下 C++ 编程主题:


示例 1:将八进制数转换为十进制

#include <iostream>
#include <cmath>
using namespace std;

int octalToDecimal(int octalNumber);

int main()
{
   int octalNumber;
   cout << "Enter an octal number: ";
   cin >> octalNumber;
   cout << octalNumber << " in octal = " << octalToDecimal(octalNumber) << " in decimal";

   return 0;
}

// Function to convert octal number to decimal
int octalToDecimal(int octalNumber)
{
    int decimalNumber = 0, i = 0, rem;
    while (octalNumber != 0)
    {
        rem = octalNumber % 10;
        octalNumber /= 10;
        decimalNumber += rem * pow(8, i);
        ++i;
    }
    return decimalNumber;
} 

输出

Enter an octal number: 2341
2341 in octal = 1249 in decimal 

在程序中,八进制数存储在变量octalNumber中,并传递给函数octalToDecimal()

该函数将用户传递的八进制数转换为其等效的十进制数,并将其返回给main()函数。

示例 2:将十进制数转换为八进制

#include <iostream>
#include <cmath>
using namespace std;

int decimalToOctal(int decimalNumber);

int main()
{
   int decimalNumber;
   cout << "Enter a decimal number: ";
   cin >> decimalNumber;
   cout << decimalNumber << " in decimal = " << decimalToOctal(decimalNumber) << " in octal";

   return 0;
}

// Function to convert decimal number to octal
int decimalToOctal(int decimalNumber)
{
    int rem, i = 1, octalNumber = 0;
    while (decimalNumber != 0)
    {
        rem = decimalNumber % 8;
        decimalNumber /= 8;
        octalNumber += rem * i;
        i *= 10;
    }
    return octalNumber;
} 

输出

Enter an decimal number: 78
78 in decimal = 116 in octal 

在程序中,十进制数存储在变量decimalNumber中,并传递给函数decimalToOctal()

该函数将用户传递的十进制数转换为其等效的八进制数,并将其返回给main()函数。