截断整数除法 [英] truncated integer division removal

查看:89
本文介绍了截断整数除法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何避免在此代码中截断整数除法?我的排序数组是 1 1 1 1 1 1 ,所以a [0] = 1和a [n]应该是1/2 = 0.5.

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;
}

推荐答案

b 变量不能包含浮点数,因为它是整数.不仅转换为 float 的时间太晚,而且将结果存储在整数变量中.除了整数结果,您还能期望什么?

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;

会带来更好的结果.

这篇关于截断整数除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆