在C ++程序中不使用'/'运算符进行除法
在本教程中,我们将学习如何在不使用除法(/)运算符的情况下对数字进行除法。
我们给了两个数字,程序应该返回除法运算的商。
我们将使用减法(-)运算符进行除法。
让我们看看解决问题的步骤。
初始化股息和除数。
如果数字为零,则返回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
结论
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下