I was solving https://codeforces.me/contest/1087/problem/D .
The following C++ solution FAILS on test case 8. I am getting "33616.5" instead of expected answer "33616.537029259414811833" .
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n, s;
cin >> n >> s;
map<int, int> graph;
for(int i = 0; i < n - 1; ++i) {
int a, b;
cin >> a >> b;
graph[a]++;
graph[b]++;
}
int leaf = 0;
for(auto& [key, val] : graph) {
if( val == 1) leaf++;
}
cout << ( 2. * s ) / leaf << endl;
return 0;
}
While the identical solution below with cout.precesion(16) passes. Can someone clearify why default cout precision wasn't handy to print double value.
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n, s;
cin >> n >> s;
map<int, int> graph;
for(int i = 0; i < n - 1; ++i) {
int a, b;
cin >> a >> b;
graph[a]++;
graph[b]++;
}
int leaf = 0;
for(auto& [key, val] : graph) {
if( val == 1) leaf++;
}
cout.precision(16); // THIS LINE IS ADDED .
cout << ( 2. * s ) / leaf << endl;
return 0;
}
When outputting floating point numbers, cout has a default precision of 6 and it truncates anything after that.
Source
Use
cout << fixed << setprecision(10)
to print 10 digits after decimal.Happened many times with me :(