十进制转化为非十进制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/

发布了7 篇原创文章 · 获赞 0 · 访问量 332

猜你喜欢

转载自blog.csdn.net/qq_45102251/article/details/105165556