博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
POJ 3077 Rounders(我的水题之路——高精度四舍五入)
阅读量:4069 次
发布时间:2019-05-25

本文共 2389 字,大约阅读时间需要 7 分钟。

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

91514459912345678444444451445446

Sample Output

20104510010000000500000002000500

Source

对于一个数字的每一位从右到左进行四舍五入操作,直到最高位的前一位,最高位仅考虑前一位的进位,不作四舍五入运算,如:
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 
#include
#include
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;}

转载地址:http://nloji.baihongyu.com/

你可能感兴趣的文章
《数据库系统概论》 第一章 绪论
查看>>
《数据库系统概论》 第二章 关系数据库
查看>>
《数据库系统概论》 第三章 关系数据库标准语言SQL
查看>>
SQL语句(二)查询语句
查看>>
SQL语句(六) 自主存取控制
查看>>
《计算机网络》第五章 运输层 ——TCP和UDP 可靠传输原理 TCP流量控制 拥塞控制 连接管理
查看>>
堆排序完整版,含注释
查看>>
二叉树深度优先遍历和广度优先遍历
查看>>
生产者消费者模型,循环队列实现
查看>>
PostgreSQL代码分析,查询优化部分,process_duplicate_ors
查看>>
PostgreSQL代码分析,查询优化部分,canonicalize_qual
查看>>
PostgreSQL代码分析,查询优化部分,pull_ands()和pull_ors()
查看>>
ORACLE权限管理调研笔记
查看>>
移进规约冲突一例
查看>>
IA32时钟周期的一些内容
查看>>
SM2椭圆曲线公钥密码算法
查看>>
获得github工程中的一个文件夹的方法
查看>>
《PostgreSQL技术内幕:查询优化深度探索》养成记
查看>>
PostgreSQL查询优化器详解之逻辑优化篇
查看>>
STM32中assert_param的使用
查看>>