编程基于栈的操作实现将任意一个非负十进制数,打印输出 与其等值的八进制数
时间: 2023-05-25 22:05:59 浏览: 104
算法步骤:
1. 创建一个空栈,将十进制数存入栈中
2. 不断进行出栈操作,每次取出栈中的一个元素(余数),将其转换为八进制数,存储在另外一个栈中。
3. 直到栈为空为止,将转换后的八进制数出栈并输出即可。
Python代码实现如下:
```python
def decimal_to_octal(decimal_num):
stack1 = [] # 创建空栈
stack2 = [] # 存储转换后的八进制数的栈
while decimal_num:
quotient, remainder = divmod(decimal_num, 8) # 获取商和余数
stack1.append(remainder) # 余数存入栈中
decimal_num = quotient # 更新原始数字
while stack1:
octal_num = stack1.pop() # 取出栈中元素
stack2.append(str(octal_num)) # 转换为字符串并存入第二个栈
return ''.join(stack2) # 将第二个栈中元素拼接成字符串并返回
print(decimal_to_octal(10)) # 12
print(decimal_to_octal(50)) # 62
```
相关问题
编程基于栈的操作实现将任意一个非负十进制数打印输出与其等值的八进制数
算法步骤:
1. 将十进制数不断除以8,将余数依次压入栈中,直到商为0为止。
2. 依次弹出栈中的元素,得到八进制数的各位数字,将其拼接成字符串。
3. 将字符串输出即可。
Python代码实现:
```python
def decimal_to_octal(decimal):
stack = []
while decimal > 0:
remainder = decimal % 8
stack.append(str(remainder))
decimal //= 8
octal = ""
while stack:
octal += stack.pop()
return octal
# 测试
print(decimal_to_octal(10)) # 输出:12
print(decimal_to_octal(123)) # 输出:173
print(decimal_to_octal(456789)) # 输出:1627465
```
编程基于栈的操作实现将任意一个非负十进制数打印输出与其等值的八进制数C语言
实现代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
void printOctal(int num) {
int remainder;
int stack[100];
int top = -1;
// 将 num 转换为八进制并压入栈中
while (num > 0) {
remainder = num % 8;
stack[++top] = remainder;
num /= 8;
}
// 依次弹出栈顶元素并输出
while (top >= 0) {
printf("%d", stack[top--]);
}
printf("\n");
}
int main() {
int num;
printf("Enter a non-negative decimal number: ");
scanf("%d", &num);
printf("Octal equivalent: ");
printOctal(num);
return 0;
}
```
该程序中,我们使用了一个栈来存储八进制数的每一位。首先,我们将输入的十进制数转换为八进制数,并将每一位压入栈中。然后,我们依次弹出栈顶元素并输出,就得到了该数的八进制表示。
阅读全文
相关推荐
![](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)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)