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
---------------------
计算a+b并以标准格式输出和——也就是说,数字必须用逗号分隔成三组(除非数字个数少于四位)。
输入规格:
每个输入文件包含一个测试用例。每种情况都包含一对整数a和b,-1000000 <= a, b <= 1000000。其中这些数字用空格隔开。
输出规范:
对于每个测试用例,您应该在一行中输出a和b的和。总和必须用标准格式写。
样例输入:
-1000000 9
样例输出:
-999,991
题解:
把数字a+b的和转化成字符串,如果第一位是负号先跳过,只要当前位的下标i满足(i + 1) % 3 等于字符串长度 % 3并且i不是最后一位,就在逐位输出的时候在该位输出后的后面加上一个逗号。
#include <stdio.h> int main(){ int a,b; scanf("%d%d",&a,&b); a+=b; //将a,b的和赋值给a if(a<0){ printf("-"); //若和为负数,则输出“-”号 a=-a; //将和转化为相反数 } int c[7],n=0,i; if(a==0) printf("0"); //若和为0,则输出0 else{ while(a>0){ c[n++]=a%10; a/=10; } //将和值的每一位数字从低位到高位依次存入数组 for(i=n-1;i>=0;i--){ printf("%d",c[i]); if(i%3==0&&i!=0) printf(","); } //从高位到低位依次输出,并加入标准格式中的“,”号 } printf("\n"); return 0; }
原文:https://www.cnblogs.com/2228212230qq/p/10887614.html