在本教程中,我们将学习如何在不使用除法(/)运算符的情况下对数字进行除法。
我们给了两个数字,程序应该返回除法运算的商。
我们将使用减法(-)运算符进行除法。
让我们看看解决问题的步骤。
初始化股息和除数。
如果数字为零,则返回0。
通过检查股息和除数的符号来存储结果是否为负。
将计数初始化为0。
编写一个循环,直到第一个数字大于或等于第二个为止。
从数字1减去数字2,然后将结果分配给数字1
递增计数器。
打印计数器。
让我们看一下代码。
#include <bits/stdc++.h>
using namespace std;
int division(int num_one, int num_two) {
if (num_one == 0) {
return 0;
}
if (num_two == 0) {
return INT_MAX;
}
bool negative_result = false;
if (num_one < 0) {
num_one = -num_one ;
if (num_two < 0) {
num_two = -num_two ;
}
else {
negative_result = true;
}
}
else if (num_two < 0) {
num_two = -num_two;
negative_result = true;
}
int quotient = 0;
while (num_one >= num_two) {
num_one = num_one - num_two;
quotient++;
}
if (negative_result) {
quotient = -quotient;
}
return quotient;
}
int main() {
int num_one = 24, num_two = 5;
cout << division(num_one, num_two) << endl;
return 0;
}输出结果如果运行上面的代码,则将得到以下结果。
4