利用栈实现十进制转八进制C++含有头文件实现文件
时间: 2024-02-04 10:03:41 浏览: 38
好的,下面是十进制转八进制的栈实现过程的 C++ 代码,包含头文件和实现文件:
栈的头文件 Stack.h:
```cpp
#ifndef STACK_H
#define STACK_H
#define MAX_SIZE 100
class Stack {
private:
int top;
int data[MAX_SIZE];
public:
Stack();
void push(int num);
int pop();
bool is_empty();
};
#endif
```
栈的实现文件 Stack.cpp:
```cpp
#include "Stack.h"
#include <iostream>
#include <cstdlib>
using namespace std;
Stack::Stack() {
top = -1;
}
void Stack::push(int num) {
if (top == MAX_SIZE - 1) {
cout << "Stack is full" << endl;
exit(1);
}
data[++top] = num;
}
int Stack::pop() {
if (top == -1) {
cout << "Stack is empty" << endl;
exit(1);
}
return data[top--];
}
bool Stack::is_empty() {
return top == -1;
}
```
十进制转八进制的实现文件 DecimalToOctal.cpp:
```cpp
#include "Stack.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
char *decimal_to_octal(int decimal_num) {
Stack s;
while (decimal_num > 0) {
int remainder = decimal_num % 8;
s.push(remainder);
decimal_num /= 8;
}
char *octal_num = new char[s.pop() + 2];
int index = 0;
while (!s.is_empty()) {
octal_num[index++] = s.pop() + '0';
}
octal_num[index] = '\0';
return octal_num;
}
```
主函数文件 main.cpp:
```cpp
#include "Stack.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
extern char *decimal_to_octal(int decimal_num);
int main() {
int decimal_num = 123;
char *octal_num = decimal_to_octal(decimal_num);
cout << decimal_num << " in decimal is " << octal_num << " in octal" << endl;
delete[] octal_num;
return 0;
}
```
你可以将这些文件放在同一个目录下,使用编译器将这些文件编译为可执行文件,运行可执行文件即可得到结果。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)