cksharma's blog

By cksharma, history, 5 years ago, In English

I was solving https://codeforces.com/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;
}

Full text and comments »

  • Vote: I like it
  • -16
  • Vote: I do not like it