问题描述:
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
简单翻译一下这个题目:
输入两个数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];
}