如何在不使用除法运算符的情况下除以两个整数?

时间:2014-02-20 04:26:41

标签: c++

在这里compsci新手。我应该编程2个用户输入的值,并在不使用*和/运算符的情况下对它们进行乘法和除法。

我已经想出如何繁殖但不分裂......

    //Multiplication
    cin >> digit1;
    cin >> digit2;

    float product = 0;

    for (int i = 0; i < digit2; i++) product = product + digit1;
    cout << product << endl;

    return 0;

至于师我不太确定......

    cin >> digit1;
    cin >> digit2;

    float quotient = 0;

    //Enter Division operation
    cout << quotient << endl;
    return 0;

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

对于除法,可以做类似的事情(下面是digit2 / digit1):

int movingNum = 0;
int i = 0;
while(movingNum < digit2){
    // This is the counter of how many times digit1 goes into digit2, increment it
    // because the running sum is still less than digit2
    i++;

    // increment the moving sum by digit1 so that it is larger by digit1 moving through
    // the next iteration of the loop
    movingNum += digit1;
}

cout << "digit1 goes into digit2 " << i << " times.";

对于digit1 / digit2:

int movingNum = 0;
int i = 0;
while(movingNum < digit1){
    // This is the counter of how many times digit2 goes into digit1, increment it
    // because the running sum is still less than digit1
    i++;

    // increment the moving sum by digit2 so that it is larger by digit2 moving through
    // the next iteration of the loop
    movingNum += digit2;
}

cout << "digit2 goes into digit1 " << i << " times.";

这些显然是整数除法,如果两个输入不均衡,则会有余数。在上述循环之后,可以通过以下方式计算余数:

int remainder = movingNum - digit2;

如果你真的在寻找一个浮点答案/结果,这将是一个完全不同的答案。

答案 1 :(得分:2)

重复划分 减去。

示例:4/2字面意思是多少个2构成4(即商)。 因此,用除数减去除数直到除数变为零,同时保持从除数(这里为4)减去除数(这里为2)的次数。

尝试以下代码(这不是浮点答案。如果您要这样做,请告诉我!:D)。

#include<stdio.h>

int main() {

    int divi, divs, quo = 0, rem = 0;

    scanf("%d %d", &divi, &divs);

    for(rem = divi - divs; rem >= 0; rem = rem-divs) {

        if(rem < 0)                         // to ensure that the right answer is obtained when the divisor isn't a factor of dividend.
          break;
        else
          quo++;
  }

printf("%d\n", quo);

return 0;

}