PAT A1001 A+B Format

版权声明:原创文章,转载请注明出处 https://blog.csdn.net/hza419763578/article/details/88426642

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
#include<iostream>
#include<cstdio>
#include <cstring>
using namespace std;
int main(){
	int a,b,c;
	char str[10],str2[10];
	cin>>a>>b;
	c=a+b;
	sprintf(str,"%d",c);
	int len=strlen(str);
	int index=0,k=0;
	for(int i=len-1;i>=0;i--){
		if(k!=0&&k%3==0&&!(i==0&&!isdigit(str[i]))) str2[index++]=',';
		str2[index++]=str[i];
		k++;
	}
	for(int i=index-1;i>=0;i--){
		cout<<str2[i];
	}
	cout<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/hza419763578/article/details/88426642
今日推荐