【PAT】甲级1001——C语言实现

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

翻译:

1001 A+B Format (20)20 

计算a + b并以标准格式输出总和 - 也就是说,数字必须用逗号分隔成三个组(除非少于四位数)。

输入

每个输入文件都包含一个测试用例。每个案例包含一对整数a和b,其中-1000000 <= a,b <= 1000000。数字之间用空格分隔。

产量

对于每个测试用例,您应该在一行中输出a和b的总和。总和必须以标准格式编写。

关键在于:用逗号隔开每三个数,要计算好逗号的位置。

实现方式:int类型输入,使用sprintf()函数转化为字符串数组,计算好位置再输出。

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#define N 15
int main()
{
    int a, b, sum;
    char c[N];
    while ((scanf("%d %d", &a, &b) != EOF))
    {
        sum = a + b;
        if (sum < 0)
        {
            printf("-");
            sum = -sum;
        }
        sprintf(c, "%d", sum);
        for (int i=0; c[i]!='\0'; i++)
        {
            printf("%c",c[i]);
            if ((strlen(c)-i-1)%3 == 0 && i!=(strlen(c)-1))
            {
                printf(",");
            }
        }
        break;
    }
    return 0;
}

再贴一个更简单的实现方法:

#include<stdio.h>
int main()
{
  int a, b, c;
  int sum;
  c = scanf("%d%d", &a, &b);
  while( c != EOF){
        sum = a+b;
    if(sum < 0){
    printf("-");
    sum = -sum;
    }
    if(sum>=1000000){
        printf("%d,%03d,%03d\n",sum/1000000, (sum/1000)%1000, sum%1000);
    }
    else if(sum >= 1000){
        printf("%d,%03d\n",sum/1000,sum%1000);
    } else{
        printf("%d\n", sum);
    }
    exit(0);
  }
  return 0;
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值