I - Budget

Avin’s company has many ongoing projects with different budgets. His company records the budgets using numbers rounded to 3 digits after the decimal place. However, the company is updating the system and all budgets will be rounded to 2 digits after the decimal place. For example, 1.004 will be rounded down
to 1.00 while 1.995 will be rounded up to 2.00. Avin wants to know the difference of the total budget caused by the update.

Input

The first line contains an integer n (1 ≤ n ≤ 1, 000). The second line contains n decimals, and the i-th decimal ai (0 ≤ ai ≤ 1e18) represents the budget of the i -th project. All decimals are rounded to 3 digits.

Output

Print the difference rounded to 3 digits..

Sample Input

1
1.001
1
0.999
2
1.001 0.999

Sample Output

-0.001
0.001
0.000

题解:

题意概括:给你n个数(小数点后面保留三位),现在要把这些三位数全都四舍五入变成两位数。问这些数变成两位全都变成两位数之后,与改变位数之前的差值是多少。

解题思路:字符串输入,用str表示字符串的最后一位、ans统计每个数与改变位数之前的差值的1000倍,即小数点后面的第三位。如果str变成数字后小于5,说明四舍五入后会丢失这个数ans-=(str-'0').如果str变成数字后大于等于5,说明四舍五入后ans增加(10-(str-'0')).输出的时候ans再除以1000.

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <cstdio>

using namespace std;

typedef long long ll;

const int maxn=1e4+10;

int main()
{
	int n;

	while(cin>>n)
	{

		int ans=0;
		for(int i=0;i<n;i++)
		{
			string s;
			cin>>s;
			int len=s.length();
			char str=s[len-1];
			if((str-'0')<5) ans-=(str-'0');
			else ans+=(10-(str-'0'));
 		}
 		if(ans<0) cout<<"-";
 		ans=abs(ans);
 		float y=ans/1000.0;
 		printf("%.3f\n",y);
	}
	
	return 0;
}

杂记:1、只有整型才能进行求余操作。

2、 abs()求得是正数的绝对值。fabs()求得是浮点数的绝对值。两者的头文件是cmath。

3、double类型输入输出都是lf。

原创文章 99 获赞 15 访问量 7342

猜你喜欢

转载自blog.csdn.net/qq_45328552/article/details/102996495
I