一个进制转换的问题:

dawnhorizon 2003-05-19 09:50:39
就是输入n进制的数,以及n,m,要转为m进制.若长度大于7,报错;
(http://acm.zju.edu.cn/show_problem.php?pid=1334)
题目不难,但是总是wrong.
给我看看代码吧,谢谢:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;
const string str="0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ";
int main()
{
char ch;
char s[100];
int t[100];
while (cin>>ch)
{
int i=0,j=0;
for (i=0;i<100;i++)
{
s[i]=0;
t[i]=0;
}
i=0;
while (ch!=' ')
{
s[i]=ch;
i++;
cin.get(ch);
}
int from,to;
cin>>from>>to;
int sum=0;
for (j=0;j<i;j++)
{
if (int (s[j])<65)
sum+=(s[j]-48)*pow(from,i-1-j);
else sum+=(s[j]-55)*pow(from,i-1-j);
}
if (to==10)
{
if (sum>9999999)
cout<<setw(7)<<"ERROR"<<endl;
else
cout<<setw(7)<<sum<<endl;
}else if (sum==0)
cout<<setw(7)<<0<<endl;
else
{
int inc=0;
while (sum>0)
{
t[inc]=sum%to;
sum=sum/to;
inc++;
}

if (inc>7)
cout<<setw(7)<<"ERROR";
else
{
cout<<setw(8-inc);
for (j=inc-1;j>=0;j--)
cout<<str[t[j]];
}
cout<<endl;
}
}
return 0;
}
...全文
23 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
lymgf 2003-05-20
  • 打赏
  • 举报
回复
终于搞清楚了,setw(n)产生的空格不等同于直接输出空格,因此被判WA,又吸取一个教训,以后作zoj的时候要注意。
lymgf 2003-05-20
  • 打赏
  • 举报
回复
把输出改为楼上的形式即可,也就是:

setw(n)改为连续输出空格,endl改为"\n".

找这种没错误的错误太难了
silentfish 2003-05-20
  • 打赏
  • 举报
回复
呵呵,也是个做ACM的兄弟
先贴下我ac的程序,呆会再帮你找bug
// accepted
// ZOJ 1334 -- Basically Speaking
#include<math.h>
#include<iostream.h>
#include<string.h>

const char bit[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

int convert(char a[],int b1,int b2)
{
int i,k,l=strlen(a);
long t=0;
char out[10]={0};
for(i=l-1;i>=0;i--)
{
int buff;
if(a[i]>'9') buff=a[i]-'A'+10;
else buff=a[i]-'0';
t=t+pow(b1,l-1-i)*buff;
}
k=0;
while(t>0)
{
int r=t%b2;
out[k]=bit[r];
k++;
t=t/b2;
}
if(k>7) cout<<" ERROR\n";
else
{
for(i=0;i<7-k;i++) cout<<" ";
for(i=k-1;i>=0;i--) cout<<out[i];
cout<<"\n";
}
return 0;
}

int main()
{
char a[10];
int base1,base2;
while(cin>>a>>base1>>base2)
{
convert(a,base1,base2);
}
return 0;
}
dawnhorizon 2003-05-20
  • 打赏
  • 举报
回复
ac了,果然是setw()的原因.多谢.

33,008

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧