PAT (Advanced Level) Practice 1001 A+B Format (20)(20 分)

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

题解1:

a,b 的范围在短整数内,两数之和也在这个范围内,使用 int 类型就足够了。

获得两数之和后,先判断是否为负整数,如果是,打印负号,再把和变成自然数。

判断和的位数,被 3 分成几份。

从高位到低位依次输出。

这里需要注意的是,如果输出是通过取余计算获得的,那么最高的 1-3 位,如果不足 3 位,是不需要补 0 的,而他们后面的其他3位数,是需要补0的。


源代码:

#include "stdio.h"
int main()
{
int a, b;
int sum;
int count=0;
int result[3];
scanf("%d%d", &a, &b);
sum = a + b;
if (sum < 0)
{
printf("-");
sum = -sum;
}
do
{
result[count] = sum % 1000;
sum = sum / 1000;
count++;

} while (sum > 0);

count--;

printf("%d", result[count]);
while(count>0)
{
printf(",");
count--;
printf("%03d", result[count]);
} ;
// system("pause");
    return 0;
}

题解2:

先求和,取正数,再把数字转换成字符串。也可以把和直接转换成字符串。输出逗号部分需要注意。

源代码2:

#include <iostream>
#include <string>
using namespace std;
int main()
{
int a, b;
int sum;
string s;
cin >> a >> b;
sum = a + b;
if (sum < 0)
{
cout<<"-";
sum = -sum;
}
s = to_string(sum);
for (int j = 0; j < s.size(); j++)
{
cout << s[j];
if ((j + 1) % 3 == s.size() % 3&&j!=s.size()-1)
cout << ",";
}
    return 0;
}


源代码3:

#include <iostream>
#include <string>
using namespace std;
int main()
{
int a, b;
int sum;
string s;
cin >> a >> b;
sum = a + b;

s = to_string(sum);
for (int j = 0; j < s.size(); j++)
{

cout << s[j];

                if (s[j]=='-') continue;

if ((j + 1) % 3 == s.size() % 3&&j!=s.size()-1)
cout << ",";
}
    return 0;
}






猜你喜欢

转载自blog.csdn.net/yi976263092/article/details/80709129