Official

A - Round decimals Editorial by mechanicalpenciI


この問題を解く方針は大きく分けて 2つあります。

\(1\) つは、文字列として読み取り、. (小数点) の前までを整数に変換、小数第一位、文字列としては . の直後あるいは最後から \(3\) 文字目が \(5\) 以上ならば \(1\) を加える、という方法です。

もう \(1\) つは、言語によりますが、それぞれの言語に準備されている四捨五入用のライブラリを用いるものです。境界、すなわち小数点以下が \(0.5\) のとき挙動が定まっていない or 適切でない、あるいは分からない時は十分小さい正数(この場合では \(0.0005\) など)を加えることで 回避することができます。
Pythonだとこの操作を行わないと\(0.5\)に対する丸めに失敗し、WAになるので気を付けてください。

c++による実装例(1つめの方針):

#include <bits/stdc++.h>

using namespace std;

#define rep(i, n) for(int i = 0; i < n; ++i)

int main(void) {
	string X;
	int a;
	int ans = 0;

	cin >> X;
	int n = X.size();
	rep(i, n - 4) {
		a = (int)(X[i] - '0');
		ans = 10 * ans + a;
	}
	if (X[n - 3] >= '5')ans++;
	cout << ans << endl;
	return 0;
}

c++による実装例(2つめの方針):

#include <bits/stdc++.h>

using namespace std;

int main(void) {
	double a;
	cin >> a;
	cout << (int)round(a+0.0005) << endl;
        //cout << (int)round(a) << endl; でも良い
	return 0;
}

pythonによる実装例(2つめの方針):

x=float(input())
print(int(round(x+0.0005,0)))

posted:
last update: