mooc第4章作业 oj1进制转换

1不同进制间的转换(30分)
题目内容:

设计一个函数toOcr(int n),实现把输入的一个十进制数转换为八进制数

输入格式:

十进制数。

输出格式:

与之对应的八进制数。

输入样例:

126

输出样例:

176

firstly, my previous 10_to_16 version:

#include <stdio.h>
#include <cmath>
#include <iostream>
using namespace std;
char arr[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
	//16(dex)-->0x10 ; 15(dex)-->0x0f;
void to_16(int i)
{
	int j=0;
	if(i<10)
	{
		cout<<i;
		return ;
	}
	else
	{
		j=i%16;
		i/=16;
		to_16(i);
		
		cout<<arr[j];
	}
}
int main()
{
	int a;
 	cin>>a;
 	to_16(a);
	return 0;
 }

or:

#include <iostream>
using namespace std;
char arr[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
	
void to_16(int i)
{
	int j=0;
if(i!=0)
{
		j=i%16;
		i/=16;
		to_16(i);
		
		cout<<arr[j];
	}
else return;		
}
int main()
{
	int a,b,n;
 	cin>>a;
 	to_16(a);
	return 0;
 }

then, the 10_to_8 version:

just change :
	j%=16;
	i/=16;
to:
	j%=8;
	i/=8;

10_to_2 version:

......

without using 递归函数(recursive):

int main ()
{
	char translate[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
	int buf[20];
	int n,i=0;
	cin>>n;
	while(n!=0)
	{
		buf[i]=n%16;
		n/=16;
		i++;
	 } 
	 for(i--;i>=0;i--)
	 {
	 	cout<<translate[ (buf[i]) ];
	 }
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值