任意进制间的转化
http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode说是水题,嘻嘻 可我写不出来,请大侠帮忙看下代码哪里错了。
#include<iostream>
using namespace std;
#include<math.h>
int main()
{
string a,c;
int *b,*d;
int t;
int s=0;
int base1,base2;
while(1)
{
cin>>a>>base1>>base2;
for(int i=1;i<=a.size();i++)
{
if(a[i]>='0'&&a[i]<'10')
b[i]=a[i]-'0';
else if(a[i]>='A'&&a[i]<='F')
b[i]=a[i]-'A'+10;
s+=b[i]*pow(base1,a.size()-i);
}
for(int i=1;;i++)
{
d[i]=s%base2;
if(d[i]>=10&&d[i]<=15)
c[i]=d[i]-10+'A';
else if(d[i]>=0&&d[i]<=9)
c[i]=d[i]-'0';
s=s/base2;
t=i;
if(s<base2)
{
d[i+1]=s;
if(d[i+1]>=10&&d[i+1]<=15)
c[i+1]=d[i+1]-10+'A';
else if(d[i+1]>=0&&d[i+1]<='F')
c[i+1]=d[i+1]-'0';
break;
}
}
for(int i=t;i>0;i++)
cout<<c[i];
cout<<endl;
}
return 0;
}
[解决办法]
#include<iostream>using namespace std;#include<math.h>int main(){string a,c;int *b,*d;int t;int s=0;int base1,base2;while(1){cin>>a>>base1>>base2; for(int i=1;i<=a.size();i++) {if(a[i]>='0'&&a[i]<'10')b[i]=a[i]-'0'; // b只是一个指针,都没有指向的内存,使用肯定不行。前面用new申请内存再用吧 else if(a[i]>='A'&&a[i]<='F') b[i]=a[i]-'A'+10;s+=b[i]*pow(base1,a.size()-i); }for(int i=1;;i++){d[i]=s%base2; // 同 bif(d[i]>=10&&d[i]<=15)c[i]=d[i]-10+'A'; // c是一个string的类型,你把int直接赋值给string?建议了解下C++的string吧。string不等于char else if(d[i]>=0&&d[i]<=9) c[i]=d[i]-'0';s=s/base2;t=i;if(s<base2){d[i+1]=s;if(d[i+1]>=10&&d[i+1]<=15)c[i+1]=d[i+1]-10+'A'; else if(d[i+1]>=0&&d[i+1]<='F') c[i+1]=d[i+1]-'0';break;} } for(int i=t;i>0;i++) cout<<c[i];cout<<endl;}return 0;}