PAT1001-A+B Format

题目描述

1001 A+B Format (20分)

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

作者

CHEN, Yue

单位

浙江大学

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

题目分析

整体分析:

题目的要求是要求进行两个整数的相加运算,这一点并不困难,本题主要卡的地方在于要进行题目所要求的格式化输出,同时还要注意本题输入的两个整数最大皆为10的六次方,即最大为七位数,考虑最极端情况两个数均为1000000,即两数相加最大值为2000000也为七位数,同时题目中要求低于四位数直接输出即可(当前考虑的皆是在相加所得数为正整数的情况),假使相加为负值,先输出减号然后按照正整数的格式进行输出即可。

如何进行输出?

可以考虑将整数分成三种进行输出,分别是7位数,4-6位数以及4位数以下

题目解答

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	int a = 0;
	int b = 0;

	cin >> a >> b;

	int sum = a + b;
	//当两数相加值为负数时
	if (sum < 0)
	{
		//先输出负号
		cout << "-";
		//然后将负数转换成正数
		sum = -sum;
	}
	//当相加结果为七位数时
	if (sum >= 1000000)
	{
        //注意:setfill()函数所要填充的字符是在数字之前填充
        //如七位数的中间三个数字是010,最后取余得到的值为10,
        //这时想要完美输出010就需要使用setfill()函数
        //在前面填充一个‘0’
		cout << sum / 1000000
			<< "," << setw(3) << setfill('0') << (sum / 1000) % 1000
			<< "," << setw(3) << setfill('0') << sum % 1000;
	}
	//当相加结果为4-6位数时
	else if (sum >= 1000)
	{
		cout << sum / 1000 << "," << setw(3) << setfill('0') << sum % 1000;
	}
	//当相加结果为四位数以下时
	else
		cout << sum;

	system("pause");

	return 0;
}

检测结果:

思考总结:

在本题的整数格式化输出中,用到了setw()和setfill()函数,接下来介绍这两种函数的用法:

  • 在C++中,setw(int n)用来控制输出间隔
  • 例如:
  1. cout<<'s'<<setw(8)<<'a'<<endl;
  2. 则在屏幕显示
  3. s a
  4. //s与a之间有7个空格,加上a就8个位置,setw()只对其后面紧跟的输出产生作用,如上例中,表示'a'共占8个位置,不足的用空格填充。若输入的内容超过setw()设置的长度,则按实际长度输出
  • setw()默认填充的内容为空格,可以setfill()配合使用设置其他字符填充。
  • 如:
  1. cout<<setfill('*')<<setw(5)<<'a'<<endl;
  2. 则输出:
  3. ***a //4个和字符a共占5个位置。
  • 所谓域宽,就是输出的内容(数值或字符等等)需要占据多少个字符的位置,如果位置有空余则会自动补足。比如我们要设置域宽为2,那么当输出一位数1的时候输出的就是“ 1”,即在1前面加了一个空格。空格和数字1正好一共占用了两个字符的位置。
  • 我 们在设置域宽和填充字符的时候要注意几点
  1. ①设置域宽的时候应该填入*整数*,设置填充字符的时候应该填入字符
  2. ②我们可以对一个要输出的内容同时设置域宽和 填充字符,但是设置好的属性仅对下一个输出的内容有效,之后的输出要再次设置。即 cout <<setw(2) <<a <<b;语句中域宽设置仅对a有效,对b无效。
  3. ③setw和setfill 被称为输出控制符,使用时需要在程序开头写上#include "iomanip.h",否则无法使用。
#include <iostream>



#include<iomanip>



using namespace std;



int main()



{



    cout<<'s'<<setfill('*')<<setw(8)<<'a'<<endl;



    return 0;



}



 



 

输出结果如下:

img

吾生也有涯,而知也无涯
原文地址:https://www.cnblogs.com/daimasanjiaomao/p/13795050.html