PTA-1001 A+B Format (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 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^6~10^6,從後往前按三個一組加逗號輸出

做法:先轉化成字符串,再從後往前標記逗號的位置,再從前往後打印。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string.h>
using namespace std;
int main()
{
    int a,b;
    scanf("%d %d",&a,&b);
    int sum = a + b;
    char str[1005];
    if(sum<0)//處理負數
    {
        printf("-");
        sum = -sum;
    }
    if(!sum)//處理結果爲0的情況
    {
        printf("0");
        return 0;
    }
    int counts = 0;
    while(sum)
    {
        int temp = sum%10;
        str[counts] = temp + '0';
        counts ++;
        sum = sum/10;
    }
    int k[20] = {0};//標記逗號數組
   for(int i = 0; i < counts-1; i ++)
   {
       if((i+1)%3==0)
        k[i] = 1;
   }
   for(int i = counts - 1; i >= 0; i --)//打印
   {
       if(k[i])
        printf(",");
       printf("%c",str[i]);

   }
   return 0;

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章