天天看点

PAT 1001 A+B Format题目要求代码实现(C语言)

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

输入要求

Each input file contains one test case. Each case contains a pair of integers a and b where −106 ≤a,b≤10​6. The numbers are separated by a space.

输出要求

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.

示例输入

示例输出

代码实现(C语言)

此前尝试过纯数字型算法,发现实现起来比较繁杂且易错,因此采用把数字型转化为字符串处理

#include<stdio.h>
#include<string.h>

int main()
{
	int a, b, sum, n;	//输入量a,b,a+b,和的位数
	char s[15];			//用于存放转化为字符串的数字
	scanf("%d %d", &a, &b);
	sum = a + b;
	
	if (sum < 0)		//如果是负数就转化为正数处理
	{
		printf("-");	//且打印一个负号
		sum *= -1;
	}
	
	sprintf(s, "%d", sum);		//将数字存入字符串s
	n = strlen(s);				//获取字符串长度,为打印字符串做准备,也用于控制分隔逗号的打印
	
	for (int i = 0; i < n; i++) 
	{
		printf("%c", s[i]);		//从第一个字符开始打印
		//在每三位数之间插入一个逗号,为了防止在数的末尾也加上一个逗号,因此控制(n-i-1)!=0
		if ((n-i-1) != 0 && (n-i-1)%3 == 0) 
		printf(",");
	}
	return 0;
}
           

继续阅读