问题
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).InputEach 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.OutputFor 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 9Sample Output-999,991
题目地址:https://www.patest.cn/contests/pat-a-PRactise/1001
解答:
#include<stdio.h>#define LEN 15void FormatPrint(const long int n);int main(){ int a, b; scanf("%d %d", &a, &b); FormatPrint(a + b); return 0;}void FormatPrint(const long int n){ long int num; if (n == 0) { putchar('0'); return; } else if (n < 0) num = -n; else num = n; int i = 0; int tag = 1; char number[LEN] = { 0 }; while (num > 0) { number[i++] = '0' + num % 10; num /= 10; if (tag % 3 == 0 && num != 0) number[i++] = ','; tag++; } if (n < 0) putchar('-'); for (i = i - 1; i >= 0; i--) putchar(number[i]);}
新闻热点
疑难解答