C语言 在c中不使用除法运算符来除数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21074682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
dividing a number without using division operator in c
提问by nomorequestions
How can I divide a number with an unknown number without using these operators('*', '/', '%'). Denominator is given during runtime.
如何在不使用这些运算符的情况下将数字与未知数字相除('*', '/', '%')。分母在运行时给出。
回答by
void main(){
int a,b,i=0;
clrscr();
printf("Enter the dividend and divisor");
scanf("%d%d",&a,&b);
while(a>=b){
a=a-b;
i++;
}
printf("qoutient is :%d \n remainder : %d",i,a);
getch();
}
回答by vinayawsm
You can use this function
你可以使用这个功能
int divide(int nu, int de) {
int temp = 1;
int quotient = 0;
while (de <= nu) {
de <<= 1;
temp <<= 1;
}
//printf("%d %d\n",de,temp,nu);
while (temp > 1) {
de >>= 1;
temp >>= 1;
if (nu >= de) {
nu -= de;
//printf("%d %d\n",quotient,temp);
quotient += temp;
}
}
return quotient;
}
You can pass a numerator and a denominator to this function and get the required quotient.
您可以将分子和分母传递给此函数并获得所需的商。
回答by Anand Gupta
Simplest way:
最简单的方法:
int divideIntegers(int num, int den){
int sign = (num*den < 0)? -1 : 1;
num = abs(num);
den = abs(den);
int quo = 0;
while( (num -= den) >= 0 )
quo++;
return sign*quo;
}
回答by muzz
Below method is the implementation of binary divide considering both numbers are positive. If subtraction is a concern we can implement that as well using binary operators.
下面的方法是考虑两个数字都是正数的二进制除法的实现。如果减法是一个问题,我们也可以使用二元运算符来实现。
======
======
-(int)binaryDivide:(int)numerator with:(int)denominator
{
if (numerator ==0 || denominator ==1) {
return numerator;
}
if (denominator ==0) {
#ifdef DEBUG
NSAssert(denominator==0, @"denominator should be greater then 0");
#endif
return INFINITY;
}
// if (numerator <0) {
// numerator = abs(numerator);
// }
int maxBitDenom = [self getMaxBit:denominator];
int maxBitNumerator = [self getMaxBit:numerator];
int msbNumber = [self getMSB:maxBitDenom ofNumber:numerator];
int qoutient = 0;
int subResult = 0;
int remainingBits = maxBitNumerator-maxBitDenom;
if(msbNumber>=denominator){
qoutient |=1;
subResult = msbNumber- denominator;
}
else{
subResult = msbNumber;
}
while(remainingBits>0){
int msbBit = (numerator & (1<<(remainingBits-1)))>0?1:0;
subResult = (subResult <<1) |msbBit;
if(subResult >= denominator){
subResult = subResult-denominator;
qoutient= (qoutient<<1)|1;
}
else{
qoutient = qoutient<<1;
}
remainingBits--;
}
return qoutient;
}
-(int)getMaxBit:(int)inputNumber
{
int maxBit =0;
BOOL isMaxBitSet = NO;
for(int i=0;i<sizeof(inputNumber)*8;i++){
if( inputNumber & (1<<i) ){
maxBit = i;
isMaxBitSet=YES;
}
}
if (isMaxBitSet) {
maxBit+=1;
}
return maxBit;
}
-(int)getMSB:(int)bits ofNumber:(int)number
{
int numbeMaxBit = [self getMaxBit:number];
return number>>(numbeMaxBit -bits);
}
回答by ouah
For integer division, you can use div, ldivor lldivfunctions from the standard library:
对于整数除法,您可以使用div,ldiv或lldiv标准库中的函数:
#include <stdlib.h>
div_t div(int numer, int denom);
ldiv_t ldiv(long int numer, long int denom);
lldiv_t lldiv(long long int numer, long long int denom);
回答by Anis_Stack
your question is very vague, but I can give you a particular case of dividing a number with 2. it can be performed by a bit shift operation that shifts the number one place to the right. This is a form of strength reduction optimization.
你的问题很模糊,但我可以给你一个将数字除以 2 的特殊情况。它可以通过将数字向右移动一位的位移操作来执行。这是强度降低优化的一种形式。
For example, 1101000 in binary (the decimal number 104), shifted one place to the right, is 0110100 (the decimal number 52): the lowest order bit, a 1, is removed. Similarly, division by any power of two (2 pow k) may be performed by right-shifting k positions. Because bit shifts are often much faster operations than division.
例如,二进制中的 1101000(十进制数 104),向右移动一位,为 0110100(十进制数 52):最低位的 1 被删除。类似地,可以通过右移 k 个位置来执行除以任何 2 的幂 (2 pow k)。因为位移通常比除法快得多。
code to test that :
代码来测试:
#include <stdio.h>
main()
{
int i = 104;
int k = 3; //
int j = i >> k ; //==> i / 2 pow k
printf("j = %d \n",j);
}
回答by Timber
This is a very simple approach to the problem; using loops and basic [+-]operators.
这是解决问题的一种非常简单的方法;使用循环和基本的 [+-] 运算符。
If you need an answer in decimals, you could use a times_ten and divide_by_ten function. In that case, you should take a look at the atoi()function; times_ten would extract the integer in a char-array, adding a '0' in the end before converting it back to integer. divide_by_ten would store the last character of an integer, substract this character with a '.' and adding the stored last digit back to the array before converting it back to integer. Atoi() will round the integer based on the decimal which we manipulated in the char-array.
如果您需要小数形式的答案,您可以使用 times_ten 和divide_by_ten 函数。在这种情况下,您应该查看atoi()函数;times_ten 将提取字符数组中的整数,在将其转换回整数之前在末尾添加一个“0”。divide_by_ten 将存储一个整数的最后一个字符,用'.'减去这个字符。并将存储的最后一位数字添加回数组,然后再将其转换回整数。Atoi() 将根据我们在字符数组中操作的小数来舍入整数。
Heres a version only supporting integer results, with an extra function (leftover_division()) replacing the '%'-operator. [b]Passing pointers to integers instead of regular integers to the divide_rounded() function and adjusting the value of 'a' in divide_rounded() should make the leftover function redundant, saving a lot of calculation time if you'd need to know the lefover.[/b]
这是一个仅支持整数结果的版本,用一个额外的函数 (leftover_division()) 替换了 '%'-operator。[b] 将指向整数而不是常规整数的指针传递给divide_rounded() 函数并调整divide_rounded() 中'a' 的值应该使剩余的函数变得多余,如果您需要知道剩下的。[/b]
#include <stdio.h>
#include <stdlib.h>
int divide_rounded(int a, int b){
int outcome_rounded = 0;
while(a > b){
a = a - b;
outcome_rounded ++;
}
return outcome_rounded;
}
int leftover_division(int a, int b){
while (a >= b){
a = a - b;
}
return a;//this will return remainder
}
main(){
int number = 20;
int divisor = 3;
int outcome;
int leftover;
outcome = divide_rounded(number, divisor);
leftover = leftover_division(number, divisor);
printf("[%d] divided by [%d] = [%d] + [%d]\n", number, divisor, outcome, leftover);
}
}
回答by Sam
Psuedo code in python for divide by constant
python中用于除以常数的伪代码
n_bits = Number of bits of input over which division is expected to be accurate
n_bits = 期望除法准确的输入位数
den = divisor
den = 除数
prec = int(math.ceil(math.log(den,2)))
shift = n_bits + prec
mult = int(math.ceil((1<<shift)/float(den)))
answer = (x*mult) >> shift
err = sum([round(x/den) - ((x*mult) >> shift) for x in range(1<<n_bits)])
Multiplication can be implemented with shifts and adds
乘法可以通过移位和加法来实现

