hdu6575Budget

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
 
中文题意:给定一个数n,然后接下来给n个小数(小数点后都是三位),问你将这些小数四舍五入到两位小数后的和减去原先小数的和的值(保留三位小数)
错误:刚开始,我是用double来接收每个小数,然后将其*1000赋值给一个整型变量a,再判断a%10>=5,看是舍是进位?但是我忘记了小数的范围,如果将其乘以1000之后就算是long long int 也存不下,所以wa了好几次
思路:需要的结果是四舍五入为两位小数的和减去原先三位小数的和,所以这个差值其实是只与输入的小数的小数部分有关,所以我完全可以利用字符串只接受小数的最后三位,然后再对其进行操作,至于再往后就是最基本的知识了
AC代码:

#include<iostream>
using namespace std;
int main(){
int n,a;
double s1=0,s2=0,val;
char c;
cin>>n;
for(int i=0;i<n;i++){
while(1){
cin>>c;
if(c=='.') break;
}
a=0;
for(int j=0;j<3;j++){
cin>>c;
a=a*10+c-'0';
}
val=a;
val/=1000;
s1+=val;
if(a%10>=5){
a=a/10;
a++;
}
else
a=a/10;
val=a;
val/=100;
s2+=val;

}
printf("%.3f\n",s2-s1);
return 0;
}

猜你喜欢

转载自www.cnblogs.com/sunjianzhao/p/11688528.html