十进制转化为非十进制C++代码

转化原理:
假设余数为 r ,十进制数为 n :(拆分为整数 zs ,余数 ys)
对 zs:需要将 zs 除 r 取余数,直到商为 0 停止,将余数倒序排列即可。
对 ys:需要将 ys乘 r 取整数部分,直到小数部分为 0 停止,将所得整数正序排列。

C++代码:

#include <stdio.h>
#include <stdlib.h>
#include <iostream> 
#include <string>
#include <iomanip>
#include <conio.h>
#include <time.h>
#include <math.h>
#include <memory>
#include <malloc.h>
#include <fstream>
#include <algorithm>
using namespace std;
//10->非10
int main(){
	double n,xs;int jz,zs;//xs小数,zs整数
	string s="";
	cout<<"输入一个十进制数:";
	cin>>n;
	cout<<"输入你要转化的进制:";
	cin>>jz;
	//整数部分zs
	zs=(int)n;
	xs=n-zs;
	while(zs!=0){
		s+=zs%jz>=10?(zs%jz-10)+'A':(zs%jz)+'0';
		zs/=jz;
	}
	reverse(s.begin(),s.end());//将串s反序
	
	if(xs!=0){
		if((int)n==0)
			s=s+"0.";
		else
			s=s+'.';
		//小数部分,取8位数即可
		for(int i=0;i<8;i++){
			xs*=jz;
			s+=int(xs)>=10?(int(xs)-10)+'A':int(xs)+'0';
			xs=xs-int(xs);
		}
	}
	cout<<s<<endl;
	system("pause");
	return 0;
}

此文章为原创,转载需说明出处。
我的博客:https://www.cnblogs.com/yannick99/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值