shu_1171 十->二进制转换(输入输出控制)

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值