c++语言用栈的知识编写一个程序实现十进制整数转换成其他进制(包括二进制、八进制、十六进制)的数
时间: 2024-09-22 22:08:21 浏览: 68
在C++中,我们可以使用栈数据结构来实现从十进制到其他进制(如二进制、八进制和十六进制)的转换。下面是一个简单的示例程序,它首先将输入的十进制数字分解为单个位,然后逐个推入栈并处理每个位生成相应的其他进制表示:
```cpp
#include <iostream>
#include <stack>
#include <string>
// Function to convert decimal digit into binary, octal or hexadecimal
std::string getOtherBase(int num, int base) {
std::string result;
while (num > 0) {
int remainder = num % base;
if (base == 2)
result = "01"[remainder] + result;
else if (base == 8)
result = "01234567"[remainder] + result;
else if (base == 16)
result = "0123456789abcdef"[remainder] + result;
num /= base;
}
return result;
}
// Function to convert decimal integer to other bases using stack
void decimalToOtherBases(int decimal, int target_base[]) {
std::stack<int> digits;
while (decimal != 0) {
digits.push(decimal % target_base[0]);
decimal /= target_base[0];
}
// Pop the digits from stack and print in reverse order
for (int i = digits.size() - 1; i >= 0; i--) {
std::cout << getOtherBase(digits.top(), target_base[i]) << " ";
digits.pop();
}
}
int main() {
int decimal_num;
std::cout << "Enter a decimal number: ";
std::cin >> decimal_num;
int bases[] = {2, 8, 16}; // Target bases for conversion: Binary, Octal, Hexadecimal
std::cout << "Binary representation: ";
decimalToOtherBases(decimal_num, bases);
std::cout << "\nOctal representation: ";
decimalToOtherBases(decimal_num, bases);
std::cout << "\nHexadecimal representation: ";
decimalToOtherBases(decimal_num, bases);
return 0;
}
```
当你运行这个程序时,它会提示用户输入一个十进制数,并分别打印出它的二进制、八进制和十六进制形式。
阅读全文