C++程式中不用‘/’運算子進行除法
在本教程中,我們將學習如何在不使用除法運算子(/)的情況下進行除法運算。
給定兩個數字,程式應返回除法運算的商。
我們將使用減法(-)運算子進行除法。
讓我們看看解決問題的步驟。
初始化被除數和除數。
如果數字為零,則返回0。
透過檢查被除數和除數的符號來儲存結果是否為負。
將計數器初始化為0。
編寫一個迴圈,直到數字一大於或等於數字二。
從數字一中減去數字二,並將結果賦值給數字一。
遞增計數器。
列印計數器。
示例
讓我們看看程式碼。
#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
結論
如果您在本教程中有任何疑問,請在評論區提出。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP