1001 A+B Format (20 分)

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 −106≤a,b≤106. 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<cstdio>
#include<cstring>
int main(){
	long long a, b;//两个数相加之后用int也许会溢出
	scanf("%lld%lld",&a,&b);
	long long sum = a + b;
	char z[10];//用来存放求和后的数,一个个放进去
	int len = 0, flag = 0;
	long long sum1 = sum < 0 ? -sum : sum;//将负的和转换为正的,当然也可以用绝对值函数
	do{
		z[len++] = '0' + sum1 % 10;
		if(len % 3 == 0) flag++;//用来记录需要添加多少个标点
		sum1 = sum1 / 10;
	}while(sum1 != 0);
	z[len] = '\0';
	for(int i = 0; i < len / 2; i++){
		int temp = z[i];
		z[i] = z[len - 1 - i];
		z[len - 1 - i] = temp;
	}
	if(sum < 0) printf("-");//如果和是负数,那么我们先把符号输出
	for(int i = 0; i < len + flag;i++){
			if(len - i != 0 && (len - i) % 3 == 0 && i != 0) printf(",");//因为标点是从后算起的,所以用len-i,但是注意无论是第一位数字前面还是最后一位数字后面都不应该有逗号
			printf("%c",z[i]);一个个输出
	}
	return 0;
	
	
}
上一篇:Python实例29:利用python自动创建多个Excel表格


下一篇:HBASE基础(3):语法(1)shell操作 (1) DDL namespace/表的操作