人生列车

follow on!success!

导航

double类型之四舍五入

题目:

A - Tutor
Time Limit:1000MS     Memory Limit:65535KB     64bit IO Format:%I64d & %I64u

Description

Lilin was a student of Tonghua Normal University. She is studying at University of Chicago now. Besides studying, she worked as a tutor teaching Chinese to Americans. So, she can earn some money per month. At the end of the year, Lilin wants to know his average monthly money to decide whether continue or not. But she is not good at calculation, so she ask for your help. Please write a program to help Lilin to calculate the average money her earned per month.
 

Input

The first line contain one integer T, means the total number of cases. 
Every case will be twelve lines. Each line will contain the money she earned per month. Each number will be positive and displayed to the penny. No dollar sign will be included.
 

Output

The output will be a single number, the average of money she earned for the twelve months. It will be rounded to the nearest penny, preceded immediately by a dollar sign without tail zero. There will be no other spaces or characters in the output.
 

Sample Input

2 100.00 489.12 12454.12 1234.10 823.05 109.20 5.27 1542.25 839.18 83.99 1295.01 1.75 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00 100.00
 

Sample Output

$1581.42
$100
分析:整体来说题目理解相当容易,只要是将题目意思搞定就可以敲出一行得到结果的代码。但是在处理四舍五入的问题时总是没法好好的搞定。而且这也不是第一次遇见这类东西了。现在先上关键代码后分析。
 1 #include <iostream>
 2 #include <cstdio>
 3 
 4 using namespace std;
 5 
 6 int main(){
 7     int t;
 8     double a;
 9     cin>>t;
10     while(t--){
11         double sum = 0;
12         for(int i = 0;i < 12; i++){
13             cin>>a;
14             sum+=a;
15         }
16         sum/=12;
17         int zhangjie = (int)(sum * 1000);
18         zhangjie+=5;
19         zhangjie/=10;
20         sum=zhangjie/100.0;
21         if((int)(sum*100)%10!=0)
22         printf("$%.2lf\n",sum);
23         else if((int)(sum*10)%10!=0)
24         printf("$%.1lf\n",sum);
25         else printf("$%.0lf\n",sum);
26     }
27 return 0;
28 };
View Code
int zhangjie = (int)(sum * 1000);
        zhangjie+=5;
        zhangjie/=10;
运算的结果是要求保留到小数点后两位,然后当然它就是和小数点的后三位是相关连的。我们先将结果*1000后取整,相当于将后面所有的部分全部的给去掉。然后的加五是为了实现四舍五入的效果。最后的除法也是为了去掉最后一位。在这里最关键的一点就是要十分的清楚,int和除法这两种操作都是直接的将最后面的部分给去掉。
然后就是在实现浮点数四舍五入的过程中,有函数ceil和函数floor可以实现的,
比如这个:
int round(double x)
{
return (x - floor(x) >= 0.5) ? (int)ceil(x) : (int)floor(x);
}

posted on 2014-09-06 12:11  tianxia2s  阅读(1584)  评论(1编辑  收藏  举报