PAT-A 1001. A+B Format (20)(20 分)

https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400

1001 A+B Format (20)(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

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

do while ,不需要判断sum!=0,因为先执行循环体

#include <iostream>
#include<cstdio>
using namespace std; 

int main(int argc, char** argv) {
	int a,b;
	cin>>a>>b;
	int sum=a+b;
	if(sum<0){
		printf("-");
		sum=-sum;
	}
	int num[10001];
	int index=0;
	do{
		num[index++]=sum%10;
		sum/=10;
	}while(sum!=0);
	for(int i=index-1;i>=0;i--){
		printf("%d",num[i]);
		if(i>0&&i%3==0){
			printf(",");
		}
	}
	return 0;
}

while需要判断sum!=0,因为后执行循环体,需要先判断

#include <iostream>
#include<cstdio>
using namespace std; 

int main(int argc, char** argv) {
	int a,b;
	cin>>a>>b;
	int sum=a+b;
	if(sum<0){
		printf("-");
		sum=-sum;
	}
	int num[10001];
	int index=0;
	if(sum==0){
		num[index++]=0;
	}
	while(sum!=0){
		num[index++]=sum%10;
		sum/=10;
	}
	for(int i=index-1;i>=0;i--){
		printf("%d",num[i]);
		if(i>0&&i%3==0){
			printf(",");
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qian2213762498/article/details/81279964
今日推荐