HDU Budget
Problem Description
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
分析:
- 题意很简单,就是把带有三位小数的数字的第三位四舍五入后计算变化的值。
- 注意的是由于题目说明输入的数的范围大小位1e18位,因此使用单独的double(15~16位精度)和long double(18 ~ 19位精度),所以不使用数据类型来存储输入的数字。
- 本人第一次接触这种大的数字精度要求的数字,因此一直陷入误区取查找有没有更大的精度的数据类型满足,后来知道查找资料的过程中才发现是用字符串进行存储。
思路:
读取最后一个字符,与字符‘5’进行比较,
- 比它大的用58-‘最后一个字符’(58的原因是10+’0‘(30h)),
- 否则用该字符-’0‘
#include<iostream>
#include<algorithm>
#include<iomanip>
#include<string>
using namespace std;
int main(){
int n,len;
string a;
double sum=0;
while(cin>>n){
sum=0;
for(int i=0;i<n;i++){
cin>>a;
len=a.length();
if(a[len-1]>='5'){
sum+=58-(int)a[len-1];
}
else
sum-=a[len-1]-'0';
}
sum/=1000.0;
cout<<fixed<<setprecision(3)<<sum<<endl;
//printf("%.3lf\n",a-b);
}
return 0;
}