PAT-A 1001 A+B Format(C语言)

题目

链接:PAT (Advanced Level) Practice 1001 A+B Format

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 −10^6​​ ≤a,b≤10^6​​ . 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


思路

题目大意是输入两个取值范围在-10^610^6之间的整数,求它们的和,并输出,输出格式要每隔3位数输出一个逗号,如示例。
所以思路就是分多次输出,因为两数和最大也只有7位数,所以穷举各种可能性即可。


代码

#include<stdio.h>

int main(){
  int a, b, sum;
  scanf("%d %d", &a, &b);
  sum = a + b;
  if(sum < 0){
    printf("-");
    sum = -sum;
  }
  
  if(sum >= 1000000){      //当位数大于6时
    printf("%d,%03d,%03d", sum / 1000000, sum % 1000000 / 1000, sum % 1000);
  }
  else if(sum >= 1000){    //当位数大于3小于6时
    printf("%d,%03d", sum / 1000, sum % 1000);
  }
  else{                    //当位数小于等于3时
    printf("%d", sum);
  }
  return 0;
}

---END---

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,504评论 0 13
  • 吃完晚饭两个人在胡同里遛弯,他接到妈妈的电话。 “喂,妈” “没事儿啦,好多了,放心吧” “něi什么啊?您说清楚...
    一去三十年阅读 234评论 0 0
  • 慢慢地你会发现一个人可以离一件事越来越远,比如经历过两年的高考, 曾经经常来往的朋友 小时候玩耍度过那时候无忧无虑...
    得不到红玫瑰阅读 508评论 0 0
  • 今天放学的时候,老师叫运动员去操场练习跑步,跳远等等,我也是其中之一项目当然是有的啦!有接力赛,跳远。 今天我和汪...
    沈丹丹601阅读 123评论 0 0