ParthJha17's blog

By ParthJha17, history, 10 months ago, In English

Hey Guys,

Here's the line that didn't work: cout<<(double)((*time.begin() + *((time.end()-1)))/2.0)<<endl;

I expected this to give me the required precision of 10^-6. It didn't work for some reason. I tried many things after that and then this worked.

cout << fixed << setprecision(1) << (long double)(time.front() + time.back()) / 2.0 << endl;

Well, I understand that every solution will have either one decimal or none as the contents of time vector are integers only, but still, I'd appreciate it if someone could help me understand why the first code didn't work.

Question Link

Solution that didn't work (precision errors)

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define endl '\n'
#define tc     \
    ll tc;     \
    cin >> tc; \
    while (tc--)
#define pb push_back
#define mp make_pair
const ll MOD = 1e9 + 7;

void fastio()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
}

void solve()
{
    ll n,temp;
    cin>>n;
    vector<ll>points,time;
    for(ll i=0;i<n;++i)
    {
        cin>>temp;
        points.push_back(temp);
    }
    for(ll i=0;i<n;++i)
    {
        cin>>temp;
        time.push_back(points[i] + temp);
        time.push_back(points[i] - temp);
    }
    sort(time.begin(), time.end());
    if(n==1)
    {
        cout<<points[0]<<endl;
    }
    else
    cout<<(double)((*time.begin() + *((time.end()-1)))/2.0)<<endl;
    
}

int main()
{
    fastio();
    ll t;
    cin >> t;
    for (ll i = 1; i <= t; i++)
    {
        solve();
    }

    return 0;
}

Solution that did work

#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define endl '\n'
#define tc     \
    ll tc;     \
    cin >> tc; \
    while (tc--)
#define pb push_back
#define mp make_pair
const ll MOD = 1e9 + 7;

void fastio()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
}

void solve()
{
    ll n, temp;
    cin >> n;
    vector<ll> points, time;
    for (ll i = 0; i < n; ++i)
    {
        cin >> temp;
        points.push_back(temp);
    }
    for (ll i = 0; i < n; ++i)
    {
        cin >> temp;
        time.push_back(points[i] + temp);
        time.push_back(points[i] - temp);
    }
    sort(time.begin(), time.end());
    if (n == 1)
    {
        cout << points[0] << endl;
    }
    else
    {
        cout << fixed << setprecision(1) << (long double)(time.front() + time.back()) / 2.0 << endl;
    }
}

int main()
{
    fastio();
    ll t;
    cin >> t;
    for (ll i = 1; i <= t; i++)
    {
        solve();
    }

    return 0;
}

Thanks a lot for your help.

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

»
10 months ago, # |
  Vote: I like it 0 Vote: I do not like it

This comment explains it well.