Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

c++ - truncated integer division removal

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...