本文主要是介绍PAT甲级 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
题目大意:
每三个数输出一个逗号(不包括最前头的负号,而且是从后往前每三个)。
代码如下:
#include <iostream>
using namespace std;
int main()
{int a,b,i=0;cin>>a>>b;string s=to_string(a+b);if(s[i]=='-') cout<<s[i++];for(;i<s.size();i++){cout<<s[i];if((i+1)%3==s.size()%3&&i!=s.size()-1) cout<<",";}return 0;
}
来总结一下:
1)(i+1)%3==s.size()%3的意思就是,你第一次逗号出现时前面的个数得是你不足三位的个数是几个。(这个是从后往前三个输出一次的)
2)(i+1)%3 ==0是从前完后三个输出一次。
这篇关于PAT甲级 1001 A+B Format的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!