1. 程式人生 > >十進位制轉八進位制

十進位制轉八進位制

給一個十進位制數,輸出它的八進位制數。

由於取餘所得得到數需要逆序輸出,符合棧的特徵(後進先出),所以使用棧來完成。

原始碼: 

#include <stdio.h>
#include <stdlib.h>
typedef struct SNode{
    int date;       //資料域
    struct SNode *next;
}SNode,*Sqlist;
//入棧
void Push(Sqlist s, int e){
    Sqlist temp;
    //動態分配空間
    temp = (Sqlist*)malloc(sizeof(SNode));
    temp->date = e;
    //新插入的結點總是在s(頭結點)之後
    temp->next = s->next;
    s->next = temp;
}
void pop(Sqlist s){
    int x;
    Sqlist q;
    //將q指向頭結點的下一個
    q=s->next;
    //避免q為空
    while(q){
        //將棧頂元素給x,並輸出
        x = q->date;
        printf("%d",x);
        //釋放q
        s->next = q->next;
        free(q);
        //q指向s的下一個,也就是棧頂元素
        q = s->next;
    }
}
int main()
{
    
    int n;
    //定義一個頭結點,使他指向空
    Sqlist L;
    L = (Sqlist*)malloc(sizeof(SNode));
    L ->next = NULL;
    printf("輸入十進位制數:");
    scanf("%d",&n);
    //避免n為0
    while(n){
            //入棧
        Push(L,n%8);
        n = n/8;

    }
    printf("八進位制數為:");
    pop(L);
    return 0;
}

執行結果: