基数转换程序.cpp
来自「C++Example实用的算法:包括枚举」· C++ 代码 · 共 91 行
CPP
91 行
#include<iostream.h>
#include<string.h>
#include<stdlib.h>
string Convert(const int& num,const int& newbase);
string Reverse(const string& str);
string Convert(const int& num,const int& newbase)
{
string str;
char ch;
int remainder=0;
int quotient=num;
while(quotient>0)
{
remainder=quotient*remainder;
quotient =quotient/newbase;
itoa(remainder,&ch,10);
str=str+ch;
}
str=Reverse(str);
return str;
}
string Reverse(const string& s)
{
string str=s;
//使用指针结构转置字符串
int last=str.size();
char * s=&str[0];
char * e=&str[size-1];
char temp;
do
{
temp=*s;
*s=*e;
*e=temp;
++s;
--e;
}
while(s<e);
return str;
}
void main()
{
int num;
int base;
char quit;
do
{
do
{
cout<<"In what base shall we work(2-10)?"
<<"Please input the base:";
cin>>base;
}
while((base<2)||(base>10));
do
{
cout<<"Enter a positive docimal integer "
<<"for conversion: ";
cin>>num;
}
while(num<0);
string answer=Convert(num,base);
cout<<num<<"="<<answer<<" in base "
<<base<<endl;
cout<<endl;
cout<<"Enter Q to quit , C to continue:";
cin>>quit;
cout<<endl;
}
while((quit!='Q')&&(quit!='q'));
return;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?