Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
179 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...