[Codeforces #373 (Div. 2) C. Efim and Strange Grade] 模拟
题目链接:[Codeforces #373 (Div. 2) C. Efim and Strange Grade]
题意描述:给定一个十进制位数为
n
的小数(含整数,小数,以及小数点部分),让你做
解题思路:首先,找到小数点之后的第一个大于等于5的位。然后从后往前做四舍五入就好了, 复杂度
O(N)
。
#include <bits/stdc++.h>
using namespace std;
#define FIN freopen("input.txt","r",stdin)
#define FOUT freopen("output.txt","w",stdout)
#define fst first
#define snd second
typedef __int64 LL;
//typedef long long LL;
typedef pair<int, int> PII;
const int MAXN = 200000 + 5;
int T, N, M;
char buf[MAXN];
int dot, pos;
inline bool finish() {
return (dot == -1 || pos == -1)
}
int main() {
#ifndef ONLINE_JUDGE
FIN;
#endif // ONLINE_JUDGE
while(~scanf("%d %d", &N, &T)) {
scanf("%s", buf);
bool overflow = false;
dot = -1, pos = -1;
for(int i = 0; buf[i]; i++) {
if(buf[i] == '.') {
dot = i;
break;
}
}
for(int i = dot + 1; buf[i]; i++) {
if(buf[i] >= '5') {
pos = i;
buf[i + 1] = '\0';
break;
}
}
while(T --) {
if(finish()) break;
if(buf[dot + 1] >= '5') {
buf[dot + 1] = buf[dot] = '\0';
int j = dot - 1;
while(j >= 0 && buf[j] == '9') {
buf[j] = '0';
j --;
}
if(j < 0 && buf[j + 1] == '0') overflow = true;
else buf[j] ++;
break;
}
buf[pos] = '\0';
buf[pos - 1] ++;
if(buf[pos - 1] < '5') pos = -1;
else pos --;
}
if(overflow) printf("1");
printf("%s\n", buf);
}
return 0;
}