1001 A+B Format (20分) 模拟题输出格式

    技术2026-03-18  9

    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

     一刷:(c语言)

    #include <stdio.h> #include <stdlib.h> #include <math.h> void print(int len ,int p[]) { int i = 0; if (len%3!=0) { for (; i < len % 3; i++) { printf("%d", p[i]); } printf(","); } int count = 0; for (; i < len; i++) { printf("%d", p[i]); count++; if (count % 3 == 0 && i < len - 1) { printf(","); } } } int main() { int a=0, b=0; if(scanf("%d %d", &a, &b)==1); while (a < -1000000 || b>1000000) { if(scanf("%d %d", &a, &b)==1); } int isNegative = 0; int sum = a + b; if (sum<0) { isNegative = 1; sum = -sum; } int len = 0; int k = sum; while (k > 0) { k /= 10; len++; } int *p = (int *)malloc(sizeof(int)*len); int mask = (int)pow(10, len - 1);//分解 if (len < 4) { if (isNegative==1) { printf("%d", -sum); } else { printf("%d", sum); } } else { for (int i = 0; i < len; i++) { p[i] = sum / mask; sum %= mask; mask /= 10; } if (isNegative == 1) { printf("-"); print(len, p); } else { print(len, p); } } return 0; }

     二刷:(c++)

    #include <iostream> #include <vector> #include <algorithm> using namespace std; vector<int> v; int main() { //freopen("in.txt", "r", stdin); int a, b, sum; cin >> a >> b; sum = a + b; if (sum<0) { cout << "-"; sum = -sum; } if (sum==0) { cout << 0 << endl; return 0; } while (sum!=0) { v.push_back(sum % 10); sum /= 10; } reverse(v.begin(), v.end());//翻转数组 for (int i = 0; i < v.size(); i++) { cout << v[i]; if (v.size()>3)//只有长度大于3才需要输出逗号 { if ((i + 1) % 3 == v.size() % 3&&((i+1)!=v.size())) { cout << ","; } } } cout << endl; return 0; }

     吾:java做法:(“,”逗号是分组的分隔符)见java核心(卷1)p58!c++好像不行

    import java.io.Console; import java.util.Scanner; public class Main { public static void main(String[] args) { int a,b; Scanner in=new Scanner(System.in); a=in.nextInt(); b=in.nextInt(); int sum=a+b; System.out.printf("%,d", sum); } }

    柳:妙啊

    #include <iostream> #include <string> using namespace std; int main() { //freopen("in.txt", "r", stdin); int a, b; cin >> a >> b; string s = to_string(a + b); for (int i = 0; i < s.length(); i++) { cout << s[i]; if (s[i]=='-') { continue; } if ((i+1)%3==s.length()%3&&(i!=s.length()-1)) { cout << ","; } } return 0; }

     

    Processed: 0.018, SQL: 9