PTA-甲级-1001- A+B Format()c++实现

一、题目

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
二、解题思路
1、结果化为字符串,三个一组加逗号输出
代码如下:

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

int main() {
	int a, b;
	int sum = 0;
	char str_sum[20];

	cin >> a >> b;
	sum = a + b;
	
	sprintf(str_sum, "%d", abs(sum));

	int len = strlen(str_sum);  //和的位数
	if (sum < 0)
		cout<<"-";
	int m = len % 3;
	int i = 0;
	//从高位开始向低位逐步输出
	if (m != 0) {
		for (i = 0; i < m; i++)
			cout << str_sum[i];
        if(len > 3)        //之前忽略了不满3位数的数字不需要输出逗号
		    cout << ",";
	}
	for (; i < len; i++) {
		cout << str_sum[i];
		cout << str_sum[i + 1];
		cout << str_sum[i + 2];
		i = i + 2;
		if (i != len - 1)
			cout << ",";
	}

	return 0;
}


2、因为题目a,b所给大小限制,也可直接枚举出结果最多七位数的所有情况,分类输出:
if(sum>=1000000) //两个逗号及以上
else if(sum >= 1000) //一个逗号
else //无逗号
代码略

三、总结

1、考虑方面要详细,不然部分正确真的很气人—
2、c++printf函数
和printf函数类似,只是把数据格式化输出到字符串(数组要有足够大的空间存放)

//example 
#include <stdio.h>

int main ()
{
  char buffer [50];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a string %d chars long\n",buffer,n);
  return 0;
}

output:

[5 plus 3 is 8] is a string 13 chars long

c++中 sprintf_s()是sprintf()的安全版本,通过指定缓冲区长度来避免sprintf()存在的溢出风险。sprintf_s和sprintf的主要不同是sprintf_s对于格式化string中的格式化的字符的有效性进行了检查,而sprintf仅仅检查格式化string或者缓冲区是否是空指针。如果有错误则返回相应的错误代码。
(参考链接:https://blog.youkuaiyun.com/zyazky/article/details/52180458)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值