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。