1001. A+B Format (20)

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

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

很水的一道题目,就是输出控制,但是我想了好久

wrong

#include <stdio.h>
#include <string.h>

int main()
{
    int a,b;
    scanf("%d%d",&a,&b);
    int sum=a+b;
    int N=sum;
    int s[10];
    int i;
    int j;
    for(i=0; i<3; i++)
    {
        s[i]=N%1000;
        N=N/1000;
    }
    for(j=2; j>=0; j--)
    {
        if(sum>=0)
        {
            if(s[j]!=0&&j!=0)
                printf("%d,",s[j]);
            if(j==0)
                printf("%d",s[j]);
        }
        if(sum<0)
        {
            if(j==2)printf("-");
            if(s[j]!=0&&j!=0)
                printf("%d,",-s[j]);
            if(j==0)
                printf("%d",-s[j]);
        }
    }
    return 0;
}

提交后是部分错误
我的思路是把要格式化输出的数每三个每三个存到数组里面,再倒序输出,特殊处理最后一个,结果是部分错误;经过验证发现输入“999 1”的时候 输出为“1,0”而不是“1,000”
如果举个例子,这道题目就很好解
比方说要输出“1234567”
如果对应到数组里储存起来应该是

1 2 3 4 5 6 7
输出 1,234,567
1 2 3 4 5 6 7
6 5 4 3 2 1 0 对应数组里面的序号
6 5 4 3 2 1 0 倒序输出

可以发现1和4后面有逗号,对应数组序号6,3正好是3的倍数
但是要考虑0也是3的倍数,所if条件句中要加入'if (j % 3 == 0 && j)'“&&j”表示 j 不能为0

AC

#include <stdio.h>
#include <string.h>

int main()
{
    int a,b;
    int s[10];
    scanf("%d%d",&a,&b);
    int sum=a+b;
    int i=0;
    int flag=0;
    if(sum<0)
    {
        flag=1;
        sum=-sum;
    }
    if(sum==0)
        printf("0");
    while(sum!=0)
    {
        s[i++]=sum%10;
        sum=sum/10;
    }
    if(flag)printf("-");
    int j;
    for (j = i - 1; j >= 0; j--)
    {
        printf("%d", s[j]);
        if (j % 3 == 0 && j) printf(",");//J不为0
    }
    return 0;
}
教主告诉我让我做PAT的题目,但是这么一道水题我都不会做,好烦躁。。。
现在做题的速度太慢了,一道水题目都要花一上午,效率太低,看样子我真得好好补基础。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值