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).

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

 

简单翻译一下这个题目:

输入两个数a,b,相加的结果要用标准方式输出,每3个数用一个逗号隔开。(除非有少于4个字符的)

针对这道题,细节的问题要解释一下:

1)题目中括号写的少于4个字符,即4位数以下,不用逗号进行分开,否则需要用逗号分开。

2)题目中一个细节没讲清,是要从低位往高位进行逗号隔离,我在写的时候,从高位开始隔逗号,造成提交部分出错

3)最后一个细节问题,负号是不作为数字进行间隔的

代码思路:

将得出的结果转换为字符数组,然后倒序将原先的数组中的参数放入一个新的字符数组中,并且每间隔3个字符,加一个逗号,然后倒序输出新的字符数组即可。细节在于处理负号与逗号之间的关系。

代码:

#include<iostream>
#include<string>
#include<string.h>
#include<stdio.h>
using namespace std;

int main()
{
	int a, b, c;
	cin >> a >> b;
	c = a + b;
	char ch[10],tmp[15];
	string str = to_string(c);
	strcpy_s(ch, str.c_str());
	int num = strlen(ch);
	int count;
	int j = 0;
	for (int i = num - 1, k = 0; i >= 0; i--, j++, k++)
	{
		if (k != 0 && k % 3 == 0)
		{
			tmp[j] = ',';
			j++;
		}
		tmp[j] = ch[i];	
	}
	if (ch[0] == '-' && (num - 1) % 3 == 0)//存在负号时,且负号正好被逗号分隔开
	{
		tmp[j - 2] = '-';
		tmp[j - 1] = '\0';
	}
	else
		tmp[j] = '\0';
	int num_tmp = strlen(tmp);
	for (int i = num_tmp - 1; i >= 0; i--)
		cout << tmp[i];
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值