1.输入任意一个十进制整数,用栈实现将其转换为对应的二进制、八进制和十六进制,并打印输出,要求在devc++下写出代码
时间: 2024-11-13 10:25:17 浏览: 38
C++实现十六进制字符串转换为十进制整数的方法
将十进制整数转换成二进制、八进制和十六进制,可以使用栈数据结构以及三位一组(对于十六进制)的方式来存储数字。以下是使用Dev-C++编写的一个简单的示例代码:
```cpp
#include <iostream>
#include <stack>
using namespace std;
// Function to convert decimal to binary and push it onto the stack
void decToBinary(int num, stack<char>& binStack) {
while (num > 0) {
binStack.push((char)(num % 2 + '0')); // Convert to char and add prefix '0'
num /= 2;
}
}
// Function to convert decimal to octal and push it onto the stack
void decToOctal(int num, stack<char>& octStack) {
for (int i = 0; i < 3; i++) {
int digit = num % 8;
octStack.push((char)(digit + '0'));
num /= 8;
}
reverse(octStack.begin(), octStack.end()); // Reverse the stack since we pushed from right
}
// Function to convert decimal to hexadecimal and push it onto the stack
void decToHexadecimal(int num, stack<char>& hexStack) {
stack<char> tempStack;
for (int i = 0; i < 4; i++) {
int digit = num % 16;
if (digit < 10)
tempStack.push((char)(digit + '0'));
else
tempStack.push((char)(digit - 10 + 'A'));
num /= 16;
}
reverse(tempStack.begin(), tempStack.end());
for (auto it : tempStack)
hexStack.push(it);
}
// Print the stacks
void printStack(stack<char>& stack, string type) {
cout << "Converting to " << type << ": ";
while (!stack.empty()) {
cout << stack.top();
stack.pop();
}
cout << endl;
}
int main() {
int decimalNum;
cout << "Enter a decimal number: ";
cin >> decimalNum;
stack<char> binStack, octStack, hexStack;
decToBinary(decimalNum, binStack);
decToOctal(decimalNum, octStack);
decToHexadecimal(decimalNum, hexStack);
printStack(binStack, "Binary");
printStack(octStack, "Octal");
printStack(hexStack, "Hexadecimal");
return 0;
}
```
当你运行这个程序并输入一个十进制数时,它会输出相应的二进制、八进制和十六进制表示。
阅读全文