PAT 1001 A+B Format
题目描述
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).
计算 a+b,输出标准形式下的和,这个数必须被分成逗号隔开的三位一组,除非结果少于四位数。
思路
直接计算a+b的和,如果是负数,先打印出负号。
- 如果位数少于四位数字,直接输出。
- 如果位数大于等于四位,先将结果中的每个位数的值存到数组中,从左到右按格式输出,或者分情况讨论输出的值。
代码
#include<iostream>
#include<stack>
#include<cmath>
using namespace std;
int main()
{
int a, b, sum, i, j;
int digit = 0, front, temp, flag;
int res[7] = {-1,-1,-1,-1,-1,-1,-1};
stack <int> k;
int everyTemp, length;
scanf("%d%d",&a,&b);
sum = a + b;
if(sum < 0)
{
sum = -sum;
printf("-");
}
temp = sum;
while(temp > 0)
{
everyTemp = temp % 10;//获取尾数
k.push(everyTemp);//放入栈中
temp = temp / 10;
digit++;
}
if(digit <= 3)
{
printf("%d",sum);
return 0;
}
i = 0;
while(!k.empty())
{
everyTemp = k.top();
res[i++] = everyTemp;
k.pop();
}
front = digit % 3;//3的余数
if(front == 0)
front = 3;
for(i = 0; i < front; i++)
{
printf("%d",res[i]);
}
printf(",");
flag = 0;
for(j = 0; j < 3; j++)
{
printf("%d",res[front+j]);
}
if(res[front+j] >= 0)
{
printf(",");
for(j = 3; j < 6; j++)
{
printf("%d",res[front+j]);
}
}
return 0;
}
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
int main(){
int a, b, c;
int m, n, len, start = 0;
scanf("%d %d",&a,&b);
c = a + b;
if(c < 0)
{
printf("-");
c = -c;
}
char s[20];
sprintf(s,"%d",c);
len = strlen(s);//结果的长度
m = len / 3;
n = len % 3;
if(n == 0)
{
printf("%c%c%c",s[0],s[1],s[2]);
start = 3;
m--;
}
else if(n == 1)
{
printf("%c",s[0]);
start = 1;
}
else if(n == 2)
{
printf("%c%c",s[0],s[1]);
start = 2;
}
while(m != 0)
{
printf(",");
printf("%c%c%c",s[start],s[start+1],s[start+2]);
start = start + 3;
m--;
}
return 0;
}