PAT练习题

1001 A+B Format (20)(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

Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.

Output

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.用到函数 sprintf格式转化函数,此处主要用于将整形数据转化为字符数组,便于计算得出数组的长度和逗号的插入
         sprintf(sc,"%d",c);【头文件无特殊要求】
    2. strlen(char*)用于计算字符数组的长度
         tc = strlen(sc);
    3.string.insert(int,string) 是string里面的函数,char*不能使用,故此处使用强制转换,用于在i处前插入string
        【cstring头文件】
二、思路,采用了笨方法
    1.让c保存a b相加结果,并算出 c 的长度 tc ,同时将 c 转化为 sc 便于操作
    2.若 c 是 0 或 c 是长度小于等于 4 的负数,或 c 是长度小于 3 的正数,则直接输出
    3.若不是以上结果,则讨论 c 为负数的结果,采用插入完毕后,一起输出的思路;将数组从后向前输出,并用count计数,每当count是  3 的倍数,则输出。
      其中c < 0时,sc不能遍历到 1 (即不能在此处插入),c > 0时,不能取到 0.
三、过程中犯的错误  ①各种函数的使用不熟练,基本上都是网上百度
                    ②第一次是部分正确,因为 if else 语句用的不严谨 ,应是else if,写错成了 if if,导致两个结果的输出【100和-100】
                    ③第二次是部分正确,没有考虑到 c 是 0 的情况。
四、难度系数    
    简单
    
*/

代码如下:

 

#include
#include

using namespace std;
int main(){
    int a,b,c,tc;
    int count = 0;
    cin>>a>>b;
    c = a + b;
    char sc[256];
    sprintf(sc,"%d",c);
    tc = strlen(sc);
    
    string s = (string)sc;
    
    if((c<0&&tc<=4)||c>0&&tc<=3||c == 0)
    {
        cout<     }
    else if(c<0)
    {
        for(int i = tc-1;i > 1;i --)
        {
            count++;
            if(count%3==0)
            s.insert(i,",");
        }
        cout<     }else if(c>0)
    {
        for(int i = tc-1;i > 0;i --)
        {
            count++;
            if(count%3==0)
            s.insert(i,",");
        }
        cout<     }
    return 0;

你可能感兴趣的:(编程与基础算法,算法)