十进制和任意进制的转换

=======================

s.push()入栈

s.top()取栈顶元素

s.pop()出栈

s.empty()栈不为空

=======================


1.十进制转换成八进制/二进制

#include<iostream>
#include<stack>
//#include"windows.h"
using namespace std;

int main()
{
	int n;
	stack<int> s;
	scanf("%d", &n);
	while (n)
	{
		s.push(n % 8);
		n = n / 8;
	}
	while (!s.empty())
	{
		printf("%d", s.top());
		s.pop();
	}
	//system("pause");
	return 0;
}

主要思想: 建栈->余数入栈->出栈







2.十进制转换成16进制

#include<iostream>
#include<stack>
//#include"windows.h"
using namespace std;

int main()
{
	int n;
	stack<int> s;
	scanf("%d", &n);
	while (n)
	{
		s.push(n % 16);
		n = n / 16;
	}
	while (!s.empty())
	{
		if (s.top() > 9&&s.top()<16)
		{
			if (s.top() == 10) printf("A");
			if (s.top() == 11) printf("B");
			if (s.top() == 12) printf("C");
			if (s.top() == 13) printf("D");
			if (s.top() == 14) printf("E");
			if (s.top() == 15) printf("F");
		}
		else
			printf("%d", s.top());
		s.pop();
	}
	printf("\n");
	//system("pause");
	return 0;
}






调用c++标准库函数进行进制转换




·       sprintf(str,"%d",value)converts to decimal base.

·       sprintf(str,"%x",value)converts to hexadecimal base.

·       sprintf(str,"%o",value)converts to octal base.






/* itoa example */
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
//#include<windows.h>
using namespace std;
int main()
{
	int i;
	char buffer[33];
	printf("Enter a number: ");
	scanf("%d", &i);
	itoa(i, buffer, 10);
	printf("decimal: %s\n", buffer);
	itoa(i, buffer, 16);
	printf("hexadecimal小写: %s\n", buffer);
	transform(buffer, buffer + strlen(buffer), buffer, toupper);//转大写 toupper:将小写转换成大写,若不是字母,则返回原值
	printf("hexadecimal大写: %s\n", buffer);
	itoa(i, buffer, 2);
	printf("binary: %s\n", buffer);
	//system("pause");
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值