PTA真题- 1001. A+B Format (20)(C语言)

发布于 / PAT-甲级 / 0 条评论

题目原文:

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

C语言代码:


#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main(){
  int a, b;
  cin >> a >> b;
  int s = a + b;
  s < 0 && cout << '-'; //如果小于0,输出负号
  string ans = to_string(abs(s));
  int len = ans.length();
  for(int i = 0; i < len; i++){
    if((len - i) % 3 == 0 && i) cout << ',';  //剩下的位数能被3整除,且不是第一位,输出逗号
    cout << ans[i];
  }
  return 0;
}

超级简单,不做过多解释了。

转载原创文章请注明,转载自: 斐斐のBlog » PTA真题- 1001. A+B Format (20)(C语言)
目前还没有评论,快来抢沙发吧~