杭电acm 1038题

本题比较简单,但是需要掌握几个小技巧,先上代码

 1 /*************************************
 2 杭电ACM 1038题,已AC
 3 
 4 **************************************/
 5 
 6 #include "iostream"
 7 
 8 using namespace std;
 9 
10 int main(void)
11 {
12     float p=3.1415927;
13     float diameter;
14     float temp;
15     int revolutions;
16     int mark=1;
17     float time;
18     float result[2];
19     cin>>diameter>>revolutions>>time;
20     while(revolutions)
21     {
22         temp=p*diameter*((float)revolutions);
23         //cout<<temp<<endl;
24         result[0]=(temp/12.0)/5280;
25         //cout<<result[0]<<endl;
26         result[0]=((int)(result[0]*100.0+0.5))/100.00;//技巧,四舍五入
27         result[1]=(temp*3600.0/time)/63360;
28         result[1]=((int)(result[1]*100.0+0.5))/100.00;
29         cout<<"Trip #"<<mark++<<": ";
30         printf("%.2f %.2f\n",result[0],result[1]);//注意表达式,这中表达是保留两位有效数字
31         cin>>diameter>>revolutions>>time;
32     }
33     return 0;
34 }

第26行代码是实现保留两位有效数字的四舍五入的技巧,例如想要3.14659,四舍五入取小数点后2位,可以将3.14659*100,得到314.659,然后再加上0.5,得到315.159,然后再取整(强制转化为int),得到315,然后再除以100.00(这里是100.00),注意,是取整后除以100,前面整个取整过程必须括号,开始没有打括号,导致程序输出结果出错。最后得到结果3.15.

 

输出结果时,%.2表示输出两位有效数字,这个也要注意下...

posted on 2014-04-14 20:14  笑侃码农  阅读(380)  评论(0编辑  收藏  举报