使用栈函数 让二进制转换为十进制或八进制
以下代码:
#include<iostream>
#include<stdlib.h>
#include<stack>
#include<math.h>
using namespace std;
void toEight(stack<char>s) {
stack<char> s1, s2;
//二进制的每三位可以合成一位八进制,让合成的这位八进制进栈
const int num1 = 3;
while (!s.empty()) {
int sum = 0;
int num2 = 0;
while (!s.empty()&&num2<num1) {
sum += (s.top()-'0')*pow(2, num2++);//一定要注意字符到数字的转换
s.pop();
}
s1.push(sum+'0');
}
cout << "转换成八进制后为:";
while (!s1.empty()) {//此时s1的栈顶是八进制的最高位,从栈顶开始依次输出就为八进制。
cout << s1.top() << ' ';
s1.pop();
}
}
int main() {
stack<char>s1,s2;
int n = s1.size();//此时n为0
char c;
int num1=0, num2=0;
cout << "输入二进制数('#'键结束):";
cin >> c;
while (c != '#') {
//C++中不能用'\n'作为判定点,cin中自动消除了'\n'
s1.push(c);//把变量进栈
s2.push(c);
cin >> c;
}
while (s1.empty()!=1) {//s1.empty为1,表示为空栈
num1 += (s1.top() - '0')*pow(2, num2++);//s1.top()表示栈顶的函数
s1.pop();//将s1出栈
}
cout << "转成十进制数为:" << num1 << endl;
toEight(s2);
return 0;
}