棧--二進制轉化

c

#include <stdio.h>

//將十進制轉換成二進制數字

int main(){
    int stack[10000],top=0;//創建一個棧
    int m;
    scanf("%d",&m);
    printf("(%d)10 == (",m);
    while(m!=0){

        stack[top++]=m%2;//將元素推進棧中
        m/=2;
    }
    while(top){
        printf("%d",stack[--top]);//取出棧頂元素,將棧頂元素彈出
    }
    printf(")2\n");
    return 0;
}

c++

#include <iostream>
#include <stack>

using namespace std;

//將十進制轉換成二進制數字

int main()
{
    int m;//m 爲數字
    cin>>m;
    stack<int>s;//創建一個棧
    cout<<"("<<m<<")10 == (";
    while(m!=0)
    {
        s.push(m%2);//將元素推進棧中
        m/=2;
    }
    while(!s.empty())
    {
        cout<<s.top();//取出棧頂元素
        s.pop();//將棧頂元素彈出
    }
    cout<<")2\n";
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章