定点数的除法C语言,定点数除法(示例代码)

public static DFix FastDiv(DFix x, DFix y)

{

long xl = x.m_rawValue;

long yl = y.m_rawValue;

long result = 0;

if (yl == 0)

{

throw new DivideByZeroException();

}

bool negative = ((xl >= 0) ^ (yl >= 0)); // 符号位

ulong remainder = (ulong)(xl >= 0 ? xl : -xl); // 余数,被除数

ulong divider = (ulong)(yl >= 0 ? yl : -yl); // 除数

ulong quotient = remainder / divider; // 商数,先求得整数部分

remainder = remainder - quotient * divider;

if(0 == remainder)

{

// 整除了,商数即结果

result = (long)(quotient << FRACTIONAL_PLACES);

}

else

{

// 需要执行小数部分的除法

ulong fraction = 0; // 小数部分

int fractionBits = 0; // 小数点位数,初始为0

while(0 != remainder && fractionBits < FRACTIONAL_PLACES)

{

remainder <<= 1; // 被除数右边补0

fractionBits++; // 小数位数增1

if (remainder >= divider)

{

// 够减,小数部分左移一位并加1,且更新被除数

fraction = (fraction << 1) + 1;

remainder -= divider;

}

else

{

// 不够减,小数部分左移一位并加0

fraction = (fraction << 1) + 0;

}

}

result = (long)((quotient << FRACTIONAL_PLACES) + (fraction & FRACTIONAL_MASK));

}

// 添加符号

result = negative ? -result : result;

return new DFix(result);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值