POJ 3077 Rounders(我的水题之路——高精度四舍五入)

Rounders
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 6419   Accepted: 4155

Description

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

Source

South Central USA 2006

对于一个数字的每一位从右到左进行四舍五入操作,直到最高位的前一位,最高位仅考虑前一位的进位,不作四舍五入运算,如:
44445 -> 44450  -> 44500 -> 45000 -> 5000
99 -> 9(+1)0-> (+1)00 -> 100

一开始拿到这道题,想的是是否可以直接对于数字进行操作,不过貌似很难,于是就想到了用数组,模拟高精度计算方法进行计算。对于数字由字符串读取进来,计算长度len,如果长度为1,就直接输出,因为一位数字,本身已经是最高位。之后从最高位开始进行考虑上前一位的进位量add,开始四舍五入,如果数字加上add大于'5',则将改为改为'0',add=1,如果小于'5',则也将该位改成‘0’,add=0.直到最高位(下标为0),加上进位即可。

注意点:
1)最高位(下标为0)不进行四舍五入。
2)最高位需要加上前一位带来了进位量。
3)最高位为‘9’,且进位量为1是,需要在整个数组前面加上'1'。
4)如果修改过数组长度,记住在末尾添加字符串结束符'\0'。

代码(1AC):
#include <cstdio>
#include <cstdlib>
#include <cstring>

char num[15];

int main(void){
    int ii, casenum;
    int add, len;
    int i, j;

    scanf("%d", &casenum);
    getchar();
    for (ii = 0; ii < casenum; ii++){
        scanf("%s", num);
        len = strlen(num);
        if (len == 1){
            printf("%s\n", num);
            continue;
        }
        for (i = len - 1, add = 0; i >= 0; i--){
            if (i != 0){
                if (num[i] + add >='5'){
                    num[i] = '0';
                    add = 1;
                }
                else{
                    add = 0;
                    num[i] = '0';
                }
            }
            else{
                if (num[i] != '9'){
                    num[i] = num[i] + add;
                }
                else{
                    if (add == 1){
                        num[i] = '0';
                    }
                    for (j = len; j > 0; j--){
                        num[j] = num[j - 1];
                    }
                    num[0] = '1';
                    num[len + 1] = '\0';
                }
            }
        }
        printf("%s\n", num);
    }
    return 0;
}


你可能感兴趣的:(Integer,input,UP,each,output,2010)