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

还是先为大家介绍一下原理吧。

假设余数为 r ,十进制数为 n :(拆分为整数 zs ,余数 ys)

对 zs:需要将 zs 除 r 取余数,直到商为 0 停止,将余数倒序排列即可。

对 ys:需要将  ys乘 r 取整数部分,直到小数部分为 0 停止,将所得整数正序排列。

C++代码:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <iostream> 
 4 #include <string>
 5 #include <iomanip>
 6 #include <conio.h>
 7 #include <time.h>
 8 #include <math.h>
 9 #include <memory>
10 #include <malloc.h>
11 #include <fstream>
12 #include <algorithm>
13 using namespace std;
14 //10->非10
15 int main(){
16     double n,xs;int jz,zs;//xs小数,zs整数
17     string s="";
18     cout<<"输入一个十进制数:";
19     cin>>n;
20     cout<<"输入你要转化的进制:";
21     cin>>jz;
22     //整数部分zs
23     zs=(int)n;
24     xs=n-zs;
25     while(zs!=0){
26         s+=zs%jz>=10?(zs%jz-10)+'A':(zs%jz)+'0';
27         zs/=jz;
28     }
29     reverse(s.begin(),s.end());//将串s反序
30     
31     if(xs!=0){
32         if((int)n==0)
33             s=s+"0.";
34         else
35             s=s+'.';
36         //小数部分,取8位数即可
37         for(int i=0;i<8;i++){
38             xs*=jz;
39             s+=int(xs)>=10?(int(xs)-10)+'A':int(xs)+'0';
40             xs=xs-int(xs);
41         }
42     }
43     cout<<s<<endl;
44     system("pause");
45     return 0;
46 }

运行结果如下:

 

 

 

此文章为原创,转载需说明出处。

posted @ 2020-03-28 18:00  YannickLi  阅读(465)  评论(0)    收藏  举报