C++ std栈函数的使用

使用栈函数 让二进制转换为十进制或八进制

以下代码:

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值