zoukankan      html  css  js  c++  java
  • PAT甲级 1001

    1001 A+B Format (20 分)

    Calculate a+b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

    Input Specification:

    Each input file contains one test case. Each case contains a pair of integers a and b where 106​​a,b106​​. The numbers are separated by a space.

    Output Specification:

    For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

    Sample Input:

    -1000000 9
    

    Sample Output:

    -999,991
    


    两种思路,第一种是今天写的,将结果预处理好存在字符串里直接输出
     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 using namespace std;
     5 int main()
     6 {
     7     long long a,b,c;
     8     char s[100];
     9     while(scanf("%lld%lld",&a,&b)!=EOF)
    10     {
    11         c=a+b;
    12         int flag=0;
    13         if(c<0)
    14         {
    15             flag=1;
    16             c=0-c;
    17         }
    18         int l=0;
    19         int g,w=0;
    20         while(c)
    21         {
    22             g=c%10;
    23             c/=10;
    24             s[l++]=g+'0';
    25             w++;
    26             if(w%3==0)s[l++]=',';
    27         }
    28         if(a+b==0)cout << "0" <<endl;
    29         else
    30         {
    31             if(flag)cout <<"-";
    32             if(s[l-1]!=',')cout << s[l-1];
    33             for(int i=l-2;i>=0;i--)
    34                 cout << s[i];
    35             cout <<endl;
    36         }
    37     }
    38 }

    另一种是去年写的,一边输出一边加逗号,翻看以前的代码被自己秀到了。。。
     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cmath>
     4 using namespace std;
     5 int main()
     6 {
     7     int a,b,c,d=1;
     8     while(scanf("%d%d",&a,&b)!=EOF)
     9     {
    10         a+=b;
    11         c=0;
    12         d=1;
    13         if(a<0){printf("-"); a=0-a;}
    14         b=a;
    15         while(a/=10)
    16         {
    17             c++;
    18             d*=10;
    19         }
    20         c++;
    21         for(;c>0;)
    22         {
    23             printf("%d",b/d);
    24             b%=d;
    25             d/=10;
    26             c--;
    27             if(!(c%3)&&c)printf(",");
    28         }
    29         printf("
    ");
    30     }
    31     return 0;
    32 }
  • 相关阅读:
    show point on image
    vec2d
    Size类型如何调用和定义
    opencv数据类型和格式的坑
    IplImage 与mat之间的转换及释放内存
    linux平台程序高精度延时问题select-usleep等
    gettimeofday的使用
    列模式编辑文本
    【linux基础】如何开机自启动某个程序-linux工具-ubuntu
    查看camera设备-linux
  • 原文地址:https://www.cnblogs.com/LowBee/p/10439147.html
Copyright © 2011-2022 走看看