-1

How do T avoid truncated integer division in this code? My sorted array is 1 1 1 1 1 1, so a[0] = 1 and a[n] should be 1 / 2 = 0.5.

int main()
{
    long long n,w;
    scanf("%lld %lld", &n, &w);
    long long arr[2*n];
    for(long long i = 0; i < 2 * n; i++)
    {
      scanf("%lld", &arr[i]);
    }
    sort(arr,arr+2*n);

    long long a = arr[0];
    long long b = (float)(arr[n]/2); // <--- this part of code
    cout << " a is " << a << endl;
    cout << " b is " << b << endl;
    long long m = min(a,b);
    cout << " m is " << m << endl;
    long long and = min(m * n + m * 2LL * n, w);
    printf("%lld", ans);
    return 0;
}
Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123
satyajeet jha
  • 163
  • 3
  • 12

3 Answers3

1

The b variable cannot hold a floating point number since it is an integer. Not only your conversion to float happens too late, but you store the result in an integer variable. How could you expect something else than a integer result ?

float b = ((float)arr[n])/2.f;

Would give better results.

Jean-Bernard Jansen
  • 7,544
  • 2
  • 20
  • 17
0

The result of:

arr[n] / 2

is an integer expression, since both operands are integers. Therefore, it performs integer division, and you lose the precision you need. Converting the (integer) result to float afterwards will not help, because the precision is just not there.

To obtain the precision you need, make both operands floats before dividing:

float b = (float) arr[n] / 2.f;
Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123
  • Surely only one needs to be a float? I often do things like `arr[n] / 2.0` in order to coerce the expression to floating point. (and now I'm wondering what the default precision is without a literal suffix) – underscore_d Feb 15 '16 at 12:00
0

How to avoid truncated integer division in this code?

Scale values by 2 and only divide by 2 in the end.

int main(void) {
    long long n,w;
    scanf("%lld %lld", &n, &w);
    long long arr[2*n];
    for(long long i = 0; i < 2 * n; i++)
    {
      scanf("%lld", &arr[i]);
    }
    sort(arr,arr+2*n);

    long long a2 = arr[0]*2;
    long long b2 = arr[n];


    printf("a*2 %lld\n",  a2);
    printf("b*2 %lld\n",  b2);
    long long m2 = min(a2,b2);
    printf("m*2 %lld\n",  m2);

    long long ans2 = min(m2 * n + m2 * 2LL * n, w*2);
    printf("ans*2 %lld\n",  ans);
    printf("ans %lld.%d\n",  ans2/2, abs(ans%2)*5);
    return 0;
}

Note: In C, make certain long long min(long long a, long long b) has that signature.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256