编程基于栈的操作实现将任意一个非负十进制数打印输出与其等值的八进制数C语言
时间: 2024-05-05 14:16:25 浏览: 11
实现代码如下:
```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;
}
```
该程序中,我们使用了一个栈来存储八进制数的每一位。首先,我们将输入的十进制数转换为八进制数,并将每一位压入栈中。然后,我们依次弹出栈顶元素并输出,就得到了该数的八进制表示。
相关问题
编程基于栈的操作实现将任意一个非负十进制数,打印输出 与其等值的八进制数C语言
的实现代码如下:
```
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define STACK_SIZE 100
typedef struct {
int top;
int data[STACK_SIZE];
} Stack;
void init(Stack *s) {
s->top = -1;
}
bool isEmpty(Stack *s) {
return s->top == -1;
}
bool isFull(Stack *s) {
return s->top == STACK_SIZE - 1;
}
void push(Stack *s, int x) {
if (isFull(s)) {
fprintf(stderr, "Stack is full\n");
exit(EXIT_FAILURE);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (isEmpty(s)) {
fprintf(stderr, "Stack is empty\n");
exit(EXIT_FAILURE);
}
return s->data[s->top--];
}
void decimalToOctal(int decimal) {
Stack s;
init(&s);
do {
push(&s, decimal % 8);
decimal /= 8;
} while (decimal > 0);
printf("Octal equivalent is: ");
while (!isEmpty(&s)) {
printf("%d", pop(&s));
}
printf("\n");
}
int main() {
int decimal;
printf("Enter a non-negative decimal number: ");
scanf("%d", &decimal);
if (decimal < 0) {
fprintf(stderr, "Invalid input\n");
exit(EXIT_FAILURE);
}
decimalToOctal(decimal);
return 0;
}
```
用C语言写程序,对于输入的任意一个非负十进制整数打印输出与其等值的八进制数
可以使用 C 语言中提供的 `printf` 函数,其中 `%o` 表示输出八进制数。具体实现如下:
```c
#include <stdio.h>
int main() {
int decimal;
printf("请输入一个非负十进制整数:");
scanf("%d", &decimal);
printf("等值的八进制数为:%o\n", decimal);
return 0;
}
```
程序首先提示用户输入一个非负十进制整数,并通过 `scanf` 函数将其存储在 `decimal` 变量中。接着使用 `printf` 函数输出 `decimal` 的八进制表示,其中 `%o` 是输出八进制数的格式控制符。最后返回 0 表示程序正常结束。