首先介绍了栈的一些简单语句
#include <bits/stdc++.h>
using namespace std;
int main(){
stack <int> a;//新建一个栈,栈名为a
//栈的存取方式为先进后出
a.push(4);//将数字4放入栈中
a.push(3);//将数字3放入栈中
a.push(2);//将数字2放入栈中
a.push(1);//将数字1放入栈中
cout<<a.top();//输出栈a的顶端元素,此时应为1
a.pop();//弹出栈中元素,先进后出,则1出来
cout<<a.top();//输出此时栈a的顶端元素,此时为2
cout<<a.empty();//判断栈是否为空
}
复习一下进制转换;
十进制转二进制,十进制转八进制,十进制转十六进制
进制转换的编程思路是将原来的十进制数字n,n%2放入栈中,让n=n/2,重复n%2,直到n=0结束。但是上课的时候,学生对于n=n/2这一步骤不是很理解,于是我又增加了一个讲解举例的步骤。假设该十进制数字n=6,然后求6对于的二进制
#include <bits/stdc++.h>
using namespace std;
int main(){
/*n=6 6%2=0放入栈中 a=6/2=3
a=3 3%2=1放入栈中 b=3/2=1
b=1 1%2=1放入栈中 c=1/2=0停止
以上学生很清楚
我们观察到后续的n的值是用不到的,为了节约
存储空间,可以将n重复利用,变为
n=6 6%2=0放入栈中 a=6/2=3 n=a 可化简为 n=6/2
n=3 3%2=1放入栈中 b=3/2=1 n=b 可化简为 n=3/2
n=1 1%2=1放入栈中 c=1/2=0 n=c 可化简为 n=1/2
归纳为n=n/2
*/
}
十进制转换二进制程序
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
stack<int>a;
cin>>n;
while(n){
a.push(n%2);
n=n/2;
}
while(!a.empty()){
cout<<a.top();
a.pop();
}
return 0;
}
十进制转换八进制类似。
十进制转换十六进制应考虑到10用A,11用B,12用C,13用D,14用E,15用F表示
方法一是新建一个可以存字符的栈,然后先进行数字转换为字符ABCDEF,再存入栈中
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
stack<char>a;
cin>>n;
while(n){
if(n%16==0)a.push('0');
if(n%16==1)a.push('1');
if(n%16==2)a.push('2');
if(n%16==3)a.push('3');
if(n%16==4)a.push('4');
if(n%16==5)a.push('5');
if(n%16==6)a.push('6');
if(n%16==7)a.push('7');
if(n%16==8)a.push('8');
if(n%16==9)a.push('9');
if(n%16==10)a.push('A');
if(n%16==11)a.push('B');
if(n%16==12)a.push('C');
if(n%16==13)a.push('D');
if(n%16==14)a.push('E');
if(n%16==15)a.push('F');
n=n/16;
}
while(!a.empty()){
cout<<a.top();
a.pop();
}
return 0;
}
方法二是直接将余数放入栈中,输出的时候进行数字转换为字符ABCDEF
//方法二
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
stack<int>a;
cin>>n;
while(n){
a.push(n%16);
n=n/16;
}
while(!a.empty()){
if(a.top()>=10&&a.top()<=16){
if(a.top()==10)cout<<"A";
if(a.top()==11)cout<<"B";
if(a.top()==12)cout<<"C";
if(a.top()==13)cout<<"D";
if(a.top()==14)cout<<"E";
if(a.top()==15)cout<<"F";
}
else{
cout<<a.top();
}
a.pop();
}
return 0;
}
好久都没有写代码了,工作之后离编程的世界越来越远,