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

运行结果如下:

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

 

 

 

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

原文链接: https://www.cnblogs.com/yannick99/p/12588540.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/338251

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午11:31
下一篇 2023年3月1日 下午11:32

相关推荐