ZOJ Problem Set–2781 Rounders

很久没有再做算法题了,做作算法题,就当是休闲娱乐了。下面是一道简单的题目,难题我也没有能力解,只能拿简单题开刀了。

Rounders


Time Limit: 1 Second      Memory Limit: 32768 KB


Introduction

For a given number, if greater than ten, round it to the nearest ten, then (if that result is greater than 100) take the result and round it to the nearest hundred, then (if that result is greater than 1000) take that number and round it to the nearest thousand, and so on ...

Input

Input to this problem will begin with a line containing a single integer n indicating the number of integers to round. The next n lines each contain a single integer x (0 <= x <= 99999999).

Output

For each integer in the input, display the rounded integer on its own line.
Note: Round up on fives.

Sample Input

9
15
14
4
5
99
12345678
44444445
1445
446

Sample Output

20
10
4
5
100
10000000
50000000
2000
500
 

其实这就是一道四舍五入的题目,以前我记得标准库有四舍五入的函数的,但是现在找了下好像又没有,真是郁闷,还弄的我找了半天,其实自己写一下这种简单的算法就只要十几秒。题目比较简单,就是从10开始一直到被除数除以除数小于1就把被除数还原到原来的值,然后返回,除数从10开始一次为10、100、1000、10000一次类推。解题代码如下:

  1: #include<iostream>
  2: 
  3: using namespace std;
  4: /*
  5:  * 四舍五入的函数
  6:  */
  7: int round(double d){
  8:     return (int)(d + 0.5);
  9: }
 10: /*
 11:  *数据处理的函数
 12:  */
 13: int format(int num){
 14:     if(num <= 10){
 15:         return num;
 16:     }
 17:     else{
 18:         int t = 10;
 19:         double f = num*1.0;
 20:         while(true){
 21:             f /= t;
 22:             if(f < 1) return f *= t; //f 小于1 就把被除数还原之后返回
 23:             f = round(f);
 24:             f *= t;
 25:             t *= 10;
 26:         }
 27:     }
 28: }
 29: int main(){
 30:     int n = 0;
 31:     while(cin>>n){
 32:         int in;
 33:         while(n-- && cin>>in){
 34:             cout<<format(in)<<endl;
 35:         }
 36:     }
 37:     return 0;
 38: }
 39: 
posted @ 2011-03-09 12:43  Gavin Lipeng Ma  阅读(1045)  评论(5编辑  收藏  举报