http://202.121.199.212/JudgeOnline/problem.php?cid=1079&pid=19
分析:主要是輸出格式控制
“對於每個n,以11位的寬度右對齊輸出n值”: 即包括該數在內一共11位,右對齊爲printf的默認方式,所以用 %11d 來解決。
另外,
輸出左對齊與右對齊,需在指定輸出長度的時候纔有意義; 如無指定長度,則輸出從行首開始,有多長輸出多長;
左對齊: %-11d
實例:
#include <stdio.h>
int main()
{
int a=123;
int b=1234;
int c=12345;
printf("%d\n%d\n%d\n",a,b,c); //沒有規定輸出長度
printf("\n%11d\n%11d\n%11d\n",a,b,c); //11位寬右對齊
printf("\n%-11d\n%-11d\n%-11d\n",a,b,c); //11位寬左對齊
return 0;
}
代碼:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
char buf[32];
while(scanf("%d",&n)!=EOF){
/* if(n>=0)
printf("%11d-->%s\n",n,itoa(n,buf,2));
else
printf("%11d-->-%s\n",n,itoa(-n,buf,2));
*/
printf("%11d-->",n);
if(!n) { printf("0\n"); continue;}
if(n<0) { n=-n; printf("-");}
string str="";
while(n){
str +=n%2 +'0';
n /=2;
}
for(int i=str.length()-1;i>=0;i--)
cout<<str[i];
cout<<endl;
}
return 0;
}